Home > Blockchain >  Replace occurences of a numpy array in another numpy array with a value
Replace occurences of a numpy array in another numpy array with a value

Time:12-15

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 !

CodePudding user response:

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

CodePudding user response:

Thanks a lot timgeb, it works. you saved me a lot of work!

  • Related