2

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

2 Answers 2

2

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)))
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.