使用 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)
出现的行?
最佳答案
您只需要查找 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])
关于python - 在 numpy 矩阵中查找匹配行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40382384/