python - 在 numpy 矩阵中查找匹配行

标签 python python-3.x numpy

使用 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/

相关文章:

python - ConvexHull 检测矩形(四边形)

python - 如何提取一些 anchor 标签之间的文本?

python - 使用 Python 根据文件内容编写 splunk 查询

为 C 和 Python 创建共享参数文件

python - 将 N 维数组广播到 (N+1) 维数组并对除 1 维之外的所有维求和

python - Cron 作业每次运行时都会写入一个新文件

python-3.x - 对 pandas 图中的 xtick 值进行舍入

python - 我怎样才能找到数据中存在弯曲/剪切的点?

python - 如何从一维数组创建二维 numpy 数组?

Python/PyQt4 : How to make a QComboBox Item draggable