简体   繁体   English

使用numpy.argwhere获取np.array中的匹配值

[英]Use numpy.argwhere to obtain the matching values in an np.array

I'd like to use np.argwhere() to obtain the values in an np.array . 我想使用np.argwhere()来获取np.array的值。

For example: 例如:

z = np.arange(9).reshape(3,3)

[[0 1 2]
 [3 4 5]
 [6 7 8]]

zi = np.argwhere(z % 3 == 0)

[[0 0]
 [1 0]
 [2 0]]

I want this array: [0, 3, 6] and did this: 我想要这个数组: [0, 3, 6]并做到了这一点:

t = [z[tuple(i)] for i in zi] # -> [0, 3, 6]

I assume there is an easier way. 我认为有一种更简单的方法。

Why not simply use masking here: 为什么不在这里简单地使用遮蔽:

z[z % 3 == 0]

For your sample matrix, this will generate: 对于您的样本矩阵,这将生成:

>>> z[z % 3 == 0]
array([0, 3, 6])

If you pass a matrix with the same dimensions with booleans as indices, you get an array with the elements of that matrix where the boolean matrix is True . 如果传递具有相同维度的矩阵作为索引的布尔值,则会得到一个数组,其中包含该矩阵的元素,其中布尔矩阵为True

This will furthermore work more efficient, since you do the filtering at the numpy level (whereas list comprehension works at the Python interpreter level). 这将更有效,因为你在numpy级别进行过滤(而列表理解在Python解释器级别工作)。

Source for argwhere argwhere来源

def argwhere(a):
    """
    Find the indices of array elements that are non-zero, grouped by element.
    ...
    """
    return transpose(nonzero(a))

np.where is the same as np.nonzero . np.wherenp.nonzero相同。

In [902]: z=np.arange(9).reshape(3,3)
In [903]: z%3==0
Out[903]: 
array([[ True, False, False],
       [ True, False, False],
       [ True, False, False]], dtype=bool)
In [904]: np.nonzero(z%3==0)
Out[904]: (array([0, 1, 2], dtype=int32), array([0, 0, 0], dtype=int32))
In [905]: np.transpose(np.nonzero(z%3==0))
Out[905]: 
array([[0, 0],
       [1, 0],
       [2, 0]], dtype=int32)

In [906]: z[[0,1,2], [0,0,0]]
Out[906]: array([0, 3, 6])

z[np.nonzero(z%3==0)] is equivalent to using I,J as indexing arrays: z[np.nonzero(z%3==0)]相当于使用I,J作为索引数组:

In [907]: I,J =np.nonzero(z%3==0)
In [908]: I
Out[908]: array([0, 1, 2], dtype=int32)
In [909]: J
Out[909]: array([0, 0, 0], dtype=int32)
In [910]: z[I,J]
Out[910]: array([0, 3, 6])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM