4

I have a numpy array full of integers, let's say

[[1,2],[3,4]]

I want to get a binary array containing 1 if the element satisfies belongs to a list, and 0 otherwise.

If I write

condition = arr == 2

I get

[[false, true], [false, false]]

which is what I want.

But what if I want to keep the elements 2 and 3 ? I tried

condition = arr in [2,3]

but it doesn't work, I get a

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I would like to do that for any possible list.

Is there any efficient way to do that? I know how to do it brutally, but I'm need to be efficient.

Thank you very much!

2 Answers2

3

how about:

np.isin(arr,[2,3])

output:

array([[False,  True],
       [ True, False]])
Binyamin Even
  • 3,318
  • 1
  • 18
  • 45
0

My 2 cents. :-)

arr = np.array([[1,2],[3,4]])
np.logical_or(arr==2,arr==3) 

output:

array([[False,  True],
      [ True, False]])
Sidon
  • 1,316
  • 2
  • 11
  • 26