小编Raj*_*raj的帖子

从NumPy ndarray中选择行

我想根据第二列中的值仅选择NumPy数组中的某些行.例如,此测试数组在第二列中具有从1到10的整数.

>>> test = numpy.array([numpy.arange(100), numpy.random.randint(1, 11, 100)]).transpose()
>>> test[:10, :]
array([[ 0,  6],
       [ 1,  7],
       [ 2, 10],
       [ 3,  4],
       [ 4,  1],
       [ 5, 10],
       [ 6,  6],
       [ 7,  4],
       [ 8,  6],
       [ 9,  7]])
Run Code Online (Sandbox Code Playgroud)

如果我只想要第二个值为4的行,那么很容易:

>>> test[test[:, 1] == 4]
array([[ 3,  4],
       [ 7,  4],
       [16,  4],
       ...
       [81,  4],
       [83,  4],
       [88,  4]])
Run Code Online (Sandbox Code Playgroud)

但是当有多个想要的值时,我如何获得相同的结果呢?

通缉名单可以是任意长度.例如,我可能想要第二列为2,4或6的所有行:

>>> wanted = [2, 4, 6]
Run Code Online (Sandbox Code Playgroud)

我提出的唯一方法是使用列表推导,然后将其转换回数组并且看起来太复杂,尽管它有效:

>>> test[numpy.array([test[x, 1] in wanted for x …
Run Code Online (Sandbox Code Playgroud)

python numpy

24
推荐指数
3
解决办法
7万
查看次数

标签 统计

numpy ×1

python ×1