Home > Software engineering >  Comparing two Numpy Arrays and keeping non-equal vectors in a third array
Comparing two Numpy Arrays and keeping non-equal vectors in a third array

Time:05-21

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 = [[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]]

I am using numpy and cant seem to figure out an efficient way to do this. 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 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.

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

CodePudding user response:

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:

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

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

CodePudding user response:

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]]
  • Related