0

Suppose I have a numpy array x = [1, 2, 3, 4, 5, ...] and I want to replace values that are not in the list a = [1, 3, 5, ...] with 0.

I tried x[x not in a] = 0 but I got the error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Anyone know the proper way that doesn't require spelling out the conditions?

2 Answers 2

3
import numpy as np
x = np.array([1, 2, 3, 4, 5])
a = np.array([1, 3, 5])
x[~np.isin(x,a)] = 0

### Output
>>> array([1, 0, 3, 0, 5])
Sign up to request clarification or add additional context in comments.

Comments

1

You should use numpy.where :

x = np.array([1, 2, 3, 4, 5])
a = np.array([1, 3, 5])
mask = np.isin(x, a)
x[mask] = 0
print(x)
>>> array([0, 2, 0, 4, 0]) 

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.