Ver*_*ion 3 python numpy python-3.x
使用 numpy,我有一个名为 的矩阵points。
points
=> matrix([[0, 2],
[0, 0],
[1, 3],
[4, 6],
[0, 7],
[0, 3]])
Run Code Online (Sandbox Code Playgroud)
如果我有 tuple (1, 3),我想找到与这些数字匹配的行points(在本例中,行索引为 2)。
我尝试使用 np.where:
np.where(points == (1, 3))
=> (array([2, 2, 5]), array([0, 1, 1]))
Run Code Online (Sandbox Code Playgroud)
这个输出的意义是什么?它可以用来查找(1, 3)出现的行吗?
你只需要沿着每一行寻找ALL matches,就像这样 -
np.where((a==(1,3)).all(axis=1))[0]
Run Code Online (Sandbox Code Playgroud)
使用给定样本涉及的步骤 -
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])
Run Code Online (Sandbox Code Playgroud)