2

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]
3
  • I rephrased it a bit and reopened the question. Commented Sep 25, 2019 at 13:06
  • What do you want returned if a value that doesn't occur in b occurs more than once in a, like if a = np.array([1,2,3,3])? Commented Sep 25, 2019 at 13:11
  • Are both of your arrays 1-dimensional ones? Depending on that you might want to adapt different strategies. The suggested setdiff1d will work only for 1D arrays. Commented Sep 25, 2019 at 14:06

2 Answers 2

7

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]
Sign up to request clarification or add additional context in comments.

4 Comments

But this only keeps unique elements, e.g. if 3 occurred twice in the original it will be only once in the result.
@RemcoGerlich I'm assuming that's what the OP wants, since the question doesn't mention this.
That's why I'm assuming he doesn't want it :-)
@RemcoGerlich I've added a workaround that keeps duplicates.
2

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.