简体   繁体   English

在numpy矩阵中找到匹配的行

[英]Finding a matching row in a numpy matrix

Using numpy, I have a matrix called points . 使用numpy,我有一个称为points的矩阵。

   points
=> matrix([[0, 2],
        [0, 0],
        [1, 3],
        [4, 6],
        [0, 7],
        [0, 3]])

If I have the tuple (1, 3) , I want to find the row in points that matches these numbers (in this case, the row index is 2). 如果我有元组(1, 3) ,我想找到与这些数字匹配的points的行(在这种情况下,行索引为2)。

I tried using np.where: 我尝试使用np.where:

np.where(points == (1, 3))
=> (array([2, 2, 5]), array([0, 1, 1]))

What is the meaning of this output? 此输出的含义是什么? Can it be used to find the row where (1, 3) occurs? 可以用来查找出现(1, 3)的行吗?

You were just needed to look for ALL matches along each row, like so - 您只需要查找每一行的ALL matches ,就像这样-

np.where((a==(1,3)).all(axis=1))[0]

Steps involved using given sample - 使用给定样本涉及的步骤-

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])

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

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