简体   繁体   English

比较两个 Numpy 数组并将不相等的向量保存在第三个数组中

[英]Comparing two Numpy Arrays and keeping non-equal vectors in a third array

I have two 2D arrays filled with vectors.我有两个用向量填充的二维数组。 I want to compare all the vectors of A to all the vectors in B and keep all the vectors of B that are unequal to the vectors in A. Like this on a small scale:我想将 A 的所有向量与 B 中的所有向量进行比较,并保留 B 的所有向量不等于 A 中的向量。像这样在小范围内:

A = [[0,1,0], [1,1,0], [1,1,1]] A = [[0,1,0], [1,1,0], [1,1,1]]

B = [[0,0,0], [1,0,0], [0,1,0], [1,1,0], [1,1,1]] B = [[0,0,0], [1,0,0], [0,1,0], [1,1,0], [1,1,1]]

Result = [[0,0,0], [1,0,0]]结果 = [[0,0,0], [1,0,0]]

I am using numpy and cant seem to figure out an efficient way to do this.我正在使用 numpy 并且似乎无法找到一种有效的方法来做到这一点。 I have tried using two for loops which seems very ineffcient and I have tried to use a for loop, but this seems very inefficient:我尝试使用两个 for 循环,这似乎非常低效,我尝试使用 for 循环,但这似乎非常低效:

for i in A: 
 for j in B: 
  if not np.all(A==B):
   print(B)

and np.where, but that does not yield the right results.和 np.where,但这不会产生正确的结果。

for i in A:
 np.where(A!=1, A, False)

This is probably easy for some people but I am very grateful for any advice.这对某些人来说可能很容易,但我非常感谢任何建议。

Kind regards,亲切的问候,

Nico尼科

If both arrays have a decent size, you can use broadcasting:如果两个数组的大小都合适,则可以使用广播:

A = np.array([[0,1,0], [1,1,0], [1,1,1]])
B = np.array([[0,0,0], [1,0,0], [0,1,0], [1,1,0], [1,1,1]])

out = B[(A!=B[:,None]).any(2).all(1)]

Output:输出:

array([[0, 0, 0],
       [1, 0, 0]])

Alternatively, you can use python sets:或者,您可以使用 python 集:

a = set(map(tuple, A))
b = set(map(tuple, B))

out = np.array(list(b.difference(a)))

You can simply use a list comprehension:您可以简单地使用列表推导:

A = [[0,1,0], [1,1,0], [1,1,1]]

B = [[0,0,0], [1,0,0], [0,1,0], [1,1,0], [1,1,1]]

[x for x in B if x not in A]

#output
[[0, 0, 0], [1, 0, 0]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM