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

Time:09-13

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)

CodePudding user response:

You want np.isin.

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

CodePudding user response:

Here is another way to solve my question:

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

CodePudding user response:

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]

CodePudding user response:

I think the best way to have several condition in a where is to use, np.logical_or, this can combine several operators as "==" or ">=" or "!="

condition = np.logical_or(arr == 23,arr == 43, arr == 64)
np.where(condition, arr, 0)
  • Related