检查不同 numpy 数组中的相同行 [英] check for identical rows in different numpy arrays
本文介绍了检查不同 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.:在本例中,数组 a
和 b
已排序,如果在您的解决方案中数组排序很重要,请提供信息
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] == b
将 a
的每一行与 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屋!
查看全文