检查不同的numpy数组中的相同行 [英] check for identical rows in different numpy arrays

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

问题描述

如何获得两个数组之间的按行比较,以得到按行的真/假数组?

how do I get a row-wise comparison between two arrays, in the result of a row-wise true/false array?

给出数据:

a = np.array([[1,0],[2,0],[3,1],[4,2]])
b = np.array([[1,0],[2,0],[4,2]])

结果步骤1:

c = np.array([True, True,False,True])

最终结果:

a = a[c]

那我怎么得到数组c ????

So how do I get the array c ????

P.S .:在此示例中,对数组ab进行了排序,如果在您的解决方案中对数组进行排序很重要,也请提供信息

P.S.: In this example the arrays a and b are sorted, please give also information if in your solution it is important that the arrays are sorted

推荐答案

以下是向量化解决方案:

Here's a vectorised solution:

res = (a[:, None] == b).all(-1).any(-1)

print(res)

array([ True,  True, False,  True])

请注意,a[:, None] == ba的每一行与b元素进行比较.然后,我们使用all + any来推断每个子数组是否存在全部为True的行:

Note that a[:, None] == b compares each row of a with b element-wise. We then use all + any to deduce if there are any rows which are all True for each sub-array:

print(a[:, None] == b)

[[[ True  True]
  [False  True]
  [False False]]

 [[False  True]
  [ True  True]
  [False False]]

 [[False False]
  [False False]
  [False False]]

 [[False False]
  [False False]
  [ True  True]]]

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

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