0

I have a 2D numpy array:

[[1,2,3,4,5],[2,4,5,6,7],[0,9,3,2,4]]

I also have a second 1D array:

[2,3,4]

I want to replace all occurences of the elements of the second array with 0 So eventually, my second array should look like

[[1,0,0,0,5],[0,0,5,6,7],[0,9,0,0,0]]

is there a way in python/numpy I can do this without using a loop.

I already checked at np.where, but the condition there is only for example where element = 1 value, and not multiple.

Thanks a lot !

1 Answer 1

3

Use numpy.isin.

>>> import numpy as np
>>> a = np.array([[1,2,3,4,5],[2,4,5,6,7],[0,9,3,2,4]])
>>> b = np.array([2,3,4])
>>> a[np.isin(a, b)] = 0
>>> a 
array([[1, 0, 0, 0, 5],
       [0, 0, 5, 6, 7],
       [0, 9, 0, 0, 0]])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.