使用numpy,我有一个名为points
的矩阵。
points
=> matrix([[0, 2],
[0, 0],
[1, 3],
[4, 6],
[0, 7],
[0, 3]])
如果我有元组(1, 3)
,我想在points
中找到与这些数字匹配的行(在这种情况下,行索引为2)。
我尝试使用np.where:
np.where(points == (1, 3))
=> (array([2, 2, 5]), array([0, 1, 1]))
此输出的含义是什么?可以用它来查找(1, 3)
出现的行吗?
答案 0 :(得分:2)
您只需要在每一行中查找ALL matches
,就像这样 -
np.where((a==(1,3)).all(axis=1))[0]
使用给定样本的步骤 -
In [17]: a # Input matrix
Out[17]:
matrix([[0, 2],
[0, 0],
[1, 3],
[4, 6],
[0, 7],
[0, 3]])
In [18]: (a==(1,3)) # Matrix of broadcasted matches
Out[18]:
matrix([[False, False],
[False, False],
[ True, True],
[False, False],
[False, False],
[False, True]], dtype=bool)
In [19]: (a==(1,3)).all(axis=1) # Look for ALL matches along each row
Out[19]:
matrix([[False],
[False],
[ True],
[False],
[False],
[False]], dtype=bool)
In [20]: np.where((a==(1,3)).all(1))[0] # Use np.where to get row indices
Out[20]: array([2])