在二维numpy数组中查找匹配的行 [英] Find matching rows in 2 dimensional numpy array

查看:1359
本文介绍了在二维numpy数组中查找匹配的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取与行匹配的二维Numpy数组的索引.例如,我的数组是这样的:

I would like to get the index of a 2 dimensional Numpy array that matches a row. For example, my array is this:

vals = np.array([[0, 0],
                 [1, 0],
                 [2, 0],
                 [0, 1],
                 [1, 1],
                 [2, 1],
                 [0, 2],
                 [1, 2],
                 [2, 2],
                 [0, 3],
                 [1, 3],
                 [2, 3],
                 [0, 0],
                 [1, 0],
                 [2, 0],
                 [0, 1],
                 [1, 1],
                 [2, 1],
                 [0, 2],
                 [1, 2],
                 [2, 2],
                 [0, 3],
                 [1, 3],
                 [2, 3]])

我想获取与行[0,1]相匹配的索引,即索引3和15.当我执行numpy.where(vals == [0 ,1])之类的操作时,我得到...

I would like to get the index that matches the row [0, 1] which is index 3 and 15. When I do something like numpy.where(vals == [0 ,1]) I get...

(array([ 0,  3,  3,  4,  5,  6,  9, 12, 15, 15, 16, 17, 18, 21]), array([0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0]))

我想要索引数组([3,15]).

I want index array([3, 15]).

推荐答案

您需要

You need the np.where function to get the indexes:

>>> np.where((vals == (0, 1)).all(axis=1))
(array([ 3, 15]),)

或者,如文档所述:

如果仅给出条件,则返回condition.nonzero()

您可以直接致电 .nonzero() .all返回的数组上:

You could directly call .nonzero() on the array returned by .all:

>>> (vals == (0, 1)).all(axis=1).nonzero()
(array([ 3, 15]),)

要分解该内容:

>>> vals == (0, 1)
array([[ True, False],
       [False, False],
       ...
       [ True, False],
       [False, False],
       [False, False]], dtype=bool)

并在该数组上调用.all方法(使用axis=1),将为您提供True,其中两个均为True:

and calling the .all method on that array (with axis=1) gives you True where both are True:

>>> (vals == (0, 1)).all(axis=1)
array([False, False, False,  True, False, False, False, False, False,
       False, False, False, False, False, False,  True, False, False,
       False, False, False, False, False, False], dtype=bool)

并获取True的索引:

>>> np.where((vals == (0, 1)).all(axis=1))
(array([ 3, 15]),)

>>> (vals == (0, 1)).all(axis=1).nonzero()
(array([ 3, 15]),)


我发现我的解决方案更具可读性,但是正如unutbu指出的那样,以下方法可能更快,并且返回与(vals == (0, 1)).all(axis=1)相同的值:


I find my solution a bit more readable, but as unutbu points out, the following may be faster, and returns the same value as (vals == (0, 1)).all(axis=1):

>>> (vals[:, 0] == 0) & (vals[:, 1] == 1)

这篇关于在二维numpy数组中查找匹配的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆