1

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

petezurich
  • 9,280
  • 9
  • 43
  • 57
BSDash
  • 13
  • 2

3 Answers3

1

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]]
Michael M.
  • 10,486
  • 9
  • 18
  • 34
0

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]]
Alain T.
  • 40,517
  • 4
  • 31
  • 51
-1

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

Dmitriy
  • 17
  • 4
  • It would be helpful to explain how this code works (and not with obvious comments and dark magic expected to be "just remember[ed]") and how it differs from the other answers. – pppery May 29 '23 at 01:51
  • @pppery i think you are wrong, many 'beginner' tutorials are written like this, you never know which line is not clear for someone(its about 'obvious'), and you contradict yourself, why should i write obvious explain 'for'? you allways can find million tutorials, and if i do, i need expl. 'def' and many more, it will be a dead end – Dmitriy May 29 '23 at 09:20