How to get the arrays not contained in another array?

87 views Asked by At

I have two Python arrays with arrays inside:

first = [[0,10],[0,11],[0,12],[0,13]]
second = [[0,10],[0,11]]

and I want to get as a result the array that is in the first one, but not in the other:

difference(first,second)
#returns [[0,12],[0,13]]

right now they are numpy arrays, but a solution with regular ones is also valid.

I tried using np.setdiff1d but it returned an array with the exclusive ints, not exclusive arrays. And I tried to iterate through the second array deleting its elements from the first one:

diff = first.view()
for equal in second:
     diff = np.delete(diff, np.where(diff == equal))

but it returned similar not useful results

3

There are 3 answers

0
Michael M. On BEST ANSWER

You could do this with regular old Python lists (not numpy arrays) and a simple list comprehension:

>>> diff = [lst for lst in first if lst not in second]
>>> diff
[[0, 12], [0, 13]]
0
Alain T. On

Using numpy, you can broadcast to compare the elements and use np.all/np.any to consolidate the comparison results into a mask:

import numpy as np

first  = np.array([[0,10],[0,11],[0,12],[0,13]])
second = np.array([[0,10],[0,11],[1,7]])

mask = ~np.any(np.all(first[:,None]==second,axis=-1),axis=-1)

print(first[mask])
[[ 0 12]
 [ 0 13]]
2
Dmitriy On

If I understand correctly, you need a function, try this:

first = [[0,10],[0,11],[0,12],[0,13]]
second = [[0,10],[0,11]]

def difference(first,second):             #declare function
    lst = []                              #declare list
    for i in first:                       #run loop
        if i not in second: lst.append(i) #just remember method
    return(lst)                           #output of this function 'lst'
difference(first,second)

I'm not sure if this is the best option, but looking by the way you ask, this method is for you