Home > Software engineering >  How to compare one 2d array with 1d array to check for elements?
How to compare one 2d array with 1d array to check for elements?

Time:06-24

So I have a matrix of 3xn. Something like

A=[[1,2,3],
 [6,2,5],
 [8,1,7],
 [2,9,8],
 [1,9,3],
 [1,4,3]]

and another list of B= [1,2,5,6,8,9]

So, if every element from A[i] is in list B then I have to delete the row. Eg. row 2,4 will need to be removed.

I wrote something like.

copy=[]
for i in A:
  for j in B:
    if int(j) in i:
      for k in B[B.index(j):]:
        if int(k) in i:
          for l in B[B.index(k):]:
            if int(l) in i:
              copy.append(i)

This keeps returning recurring values. It also removes more than what I have already written. What am I doing wrong?

I also tried

for i in A:
  copy=[x for x in i if x not in B]
  copy=np.array(copy)
  final.append(copy)

But it doesn't work.

Note: I am using numpy array for A and list for B so I always need to convert between them when I am doing comparing.

CodePudding user response:

It is quite straightforward with numpy arrays, use isin to identify values present in B, then aggregate as a single boolean with all to get rows where all values are present, invert the mask with ~ and slice:

A = np.array([[1,2,3],
              [6,2,5],
              [8,1,7],
              [2,9,8],
              [1,9,3],
              [1,4,3]])

B = np.array([1,2,5,6,8,9])
# or as list
B = [1,2,5,6,8,9]

A2 = A[~np.isin(A, B).all(1)]

output:

array([[1, 2, 3],
       [8, 1, 7],
       [1, 9, 3],
       [1, 4, 3]])

intermediates:

np.isin(A, B)
array([[ True,  True, False],
       [ True,  True,  True],
       [ True,  True, False],
       [ True,  True,  True],
       [ True,  True, False],
       [ True, False, False]])

np.isin(A, B).all(1)
array([False,  True, False,  True, False, False])

~np.isin(A, B).all(1)
array([ True, False,  True, False,  True,  True])

CodePudding user response:

Concept

Iterate through all of the elements inside A, and check if each array is a subset of B. If it is not then put the array into a result array.

Code

A=[[1,2,3],[6,2,5],[8,1,7],[2,9,8],[1,9,3],[1,4,3]]
B=[1,2,5,6,8,9]
set_B=set(B)
result=[]
for arr in A:
    if not set(arr).issubset(set_B):
        result.append(arr)
print(result)
  • Related