检查矩阵的每一行是否在另一个矩阵中[Python] [英] Check whether each row of a matrix is in another matrix [Python]

查看:803
本文介绍了检查矩阵的每一行是否在另一个矩阵中[Python]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个矩阵(或更佳的2D numpy数组),AB,具有相同的列数(为公平起见,它们具有不同的行数,但是我只是在切片两个矩阵都放在两列上),但行数不同.

I have two matrices (or, better, 2D numpy arrays), A and B, with same number of columns (well, to be fair they have a different number of rows, however I'm just slicing both matrices on two columns) but different number of rows.

我想检查A中的每一行是否在B中,以及B中正确的行索引是什么.我实际上正在使用常规循环,即

I would like to check whether every row in A is in B and what is the proper row index in B. I actually am using a regular loop, that is

for r in range(A.shape[0]):
    idx=numpy.where(numpy.all(B[:,[0,1]]==A[r,[1,2]],axis=1))
    idx=idx[0][0]

我想知道是否存在一些更聪明的技术,可以使用索引方法并避免循环.我知道numpy的in1d,但是它仅适用于一维数组.

I was wondering if there are some smarter techniques to do so, possible using indexed methods and avoiding loops. I'm aware of numpy's in1d, but it does only work on 1D arrays.

对于熟悉Matlab的读者,我正在寻找'rows'选项被触发时的ismember()行为.

For readers familiar with Matlab, I'm looking for the ismember() behaviour when the 'rows' option is triggered.

推荐答案

您可以使用

You can use a vectorized approach using NumPy broadcasting, like so -

np.argwhere((B[:,None,[0,1]] == A[:,[1,2]]).all(-1))

或者,由于您只处理2个元素的行,因此建议使用保持2D的内存有效方法,就像这样-

Alternatively, since you are dealing with rows of just 2 elements, a memory efficient approach that stays 2D could be suggested, like so -

np.argwhere((B[:,None,0] == A[:,1]) & (B[:,None,1] == A[:,2]))

输出将是(N,2)形状的数组,其中第一列为我们提供B的行索引,而第二列A为我们提供与行中所有元素匹配的内容.

The output would be (N,2) shaped array, in which the first column gives us the row indices of B and the second column of A corresponding to matches across all elements in a row.

样品运行-

In [154]: A[:,[1,2]]
Out[154]: 
array([[0, 1],
       [0, 2],
       [2, 1],
       [1, 2],
       [0, 1]])

In [155]: B[:,[0,1]]
Out[155]: 
array([[0, 1],
       [2, 2],
       [1, 2],
       [0, 2],
       [2, 1],
       [2, 1],
       [1, 0]])

In [156]: np.argwhere((B[:,None,[0,1]] == A[:,[1,2]]).all(-1))
Out[156]: 
array([[0, 0],
       [0, 4],
       [2, 3],
       [3, 1],
       [4, 2],
       [5, 2]])

这篇关于检查矩阵的每一行是否在另一个矩阵中[Python]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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