I would like to subtract element from a numpy array that don't exist in another.
Example:
a = np.array([1,2,3,4])
b = np.array([1,2])
Result:
[3, 4]
You can use Numpy's setdiff1d function:
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([1, 2])
c = np.setdiff1d(a, b)
print(c)
Output:
[3 4]
If duplicate values are not to be removed, then you can use Numpy's in1d function:
import numpy as np
a = np.array([3, 1, 4, 2, 3, 4])
b = np.array([1, 2])
c = a[~np.in1d(a, b)]
print(c)
Output:
[3 4 3 4]
If you want to keep duplicates, you can index using in1d:
>>> a = np.array([1,2,3,3])
>>> b = np.array([1,2])
>>> np.in1d(a, b) # Boolean array that says where a is in b
array([ True, True, False, False], dtype=bool)
>>> ~np.in1d(a, b)) # Boolean array that says where a is NOT in b
array([False, False, True, True], dtype=bool)
>>> a[~np.in1d(a, b)] # Use the Boolean array as index to get your answer
array([3, 3])
a = np.array([1,2,3,3])?setdiff1dwill work only for 1D arrays.