How to use np.where for more than one values?

Viewed 39

I have an array of size (1318, 1816), I would like to replace values other than that 23,43, and 64 to zero. I have tried np.where, but returns an array full of zero. can anyone help me to correct the following code:

arr=np.array(img)
labels=[23,43,64]
arr_masked= np.where(arr!=labels,0,arr)
3 Answers

You want np.isin.

arr_masked= np.where(np.isin(arr, labels), arr, 0)

Here is another way to solve my question:

arr_masked= np.where((arr != 23)*(arr != 43)*(arr != 64) , 0, arr)

Check Below using np.isin & np.where

import numpy as np

img = np.array([1,2,3,4,5])
labels = [2,5]

print(np.where(np.isin(img,labels),1,img))

Output:

[1 1 3 4 1]
Related