Home > Software engineering >  Remove rows equal in two different arrays
Remove rows equal in two different arrays

Time:11-24

I have two numpy arrays, A and B, where A is bigger than B.

A = [ 1 0 0, 2 0 0, 3 0 0, 4 0 0, 5 0 0]
B = [ 2 0 0, 5 0 0]

I need to create another array, C, which contains all rows in A with the exception of those contained in B:

C = [1 0 0, 3 0 0, 4 0 0]

How can I do it?

CodePudding user response:

If you don't care about the order and your array doesn't contain duplicates you could do the following.

A = [100, 200, 300, 400, 500]
B = [200, 500]

C = list(set(A) - set(B))

Otherwise, you could iterate over A and exclude all items that are present in B. I created set_b as it is faster to check if something is present inside a set.

A = [100, 200, 300, 400, 500]
B = [200, 500]
set_b = set(B)

C = [item for item in A if item not in set_b]

CodePudding user response:

C = np.array([x for x in A if x not in B])

By the way, I don't quite understand the spaces beween numbers.

CodePudding user response:

You can use in1d:

import numpy as np

a = np.array([[1,0,0], [2,0,0], [3,0,0], [4,0,0], [5,0,0]])
b = np.array([[2,0,0],[5,0,0]])
c = a[~np.in1d(a[:,0].astype(int), b)]
print(c)

Output:

[[1 0 0]
 [3 0 0]
 [4 0 0]]
  • Related