1

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)
rayan
  • 332
  • 1
  • 12
  • Does this answer your question? [Numpy where function multiple conditions](https://stackoverflow.com/questions/16343752/numpy-where-function-multiple-conditions) – Lucas M. Uriarte Sep 12 '22 at 08:47

3 Answers3

2

You want np.isin.

arr_masked= np.where(np.isin(arr, labels), arr, 0)
Daniel F
  • 13,620
  • 2
  • 29
  • 55
1

Here is another way to solve my question:

arr_masked= np.where((arr != 23)*(arr != 43)*(arr != 64) , 0, arr)
rayan
  • 332
  • 1
  • 12
0

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]
Abhishek
  • 1,585
  • 2
  • 12
  • 15