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?
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])
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With