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

Question:

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)
Asked By: rayan

||

Answers:

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]
Answered By: Abhishek

You want np.isin.

arr_masked= np.where(np.isin(arr, labels), arr, 0)
Answered By: Daniel F

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)
Answered By: Lucas M. Uriarte

Here is another way to solve my question:

arr_masked= np.where((arr != 23)*(arr != 43)*(arr != 64) , 0, arr)
Answered By: rayan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.