Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use numpy setdiff1d keeping the order

Tags:

python

numpy

a = np.array([1, 2, 3])
b = np.array([4, 2, 3, 1, 0])
c = np.setdiff1d(b, a)
print("c", c)

The result is c [0, 4] but the answer I want is c [4 0].

How can I do that?

like image 847
CYC Avatar asked Sep 17 '17 07:09

CYC


2 Answers

Get the mask of non-matches with np.in1d and simply boolean-index into b to retain the order of elements in it -

b[~np.in1d(b,a)]

Sample step-by-step run -

In [14]: a
Out[14]: array([1, 2, 3])

In [15]: b
Out[15]: array([4, 2, 3, 1, 0])

In [16]: ~np.in1d(b,a)
Out[16]: array([ True, False, False, False,  True], dtype=bool)

In [17]: b[~np.in1d(b,a)]
Out[17]: array([4, 0])
like image 193
Divakar Avatar answered Oct 23 '22 03:10

Divakar


If you want c to 1) have the elements of b that are not in a and 2) for them to be in the same order as they were in b you can use a list comprehension:

c = np.array([el for el in b if el not in a])

setdiff1d treats the arrays as sets and thus: 1) does not respect the order of the elements, 2) any element present more than once is treated as if it was present only once. For example this code:

a = np.array([4])
b = np.array([2, 4, 2, 1, 1])
c = np.setdiff1d(b, a)
print(c)

Will yield

[1, 2]
like image 23
Evgenii Avatar answered Oct 23 '22 02:10

Evgenii