1

like this:

>> arr = np.array([[0, 50], [100, 150], [200, 250]]) 
>>> values = [100, 200, 300] 

>>> arr in values

expect:

array([[False, False],
       [ True, False],
       [ True, False]])

result:

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

I wrote following code and it works, but this code cannot accept changing length of list

(arr==values[0]) | (arr==values[1]) | (arr==values[2])
9
  • You are using the script or the command line? Commented Aug 9, 2019 at 7:59
  • 1
    @BogdanDoicin why does that make a difference Commented Aug 9, 2019 at 8:00
  • 2
    You can use np.isin(arr,values) Commented Aug 9, 2019 at 8:03
  • @BogdanDoicin This example is written as on command line for simplification, but I want to this code use on script. Any differences in this issue? Commented Aug 9, 2019 at 8:04
  • @BlueRineS Thanks. Can you write this as answer? Commented Aug 9, 2019 at 8:06

3 Answers 3

4

Use np.isin:

import numpy as np

arr = np.array([[0, 50], [100, 150], [200, 250]])
values = [100, 200, 300]

np.isin(arr, values)

result:

array([[False, False],
       [ True, False],
       [ True, False]])
Sign up to request clarification or add additional context in comments.

Comments

0

This should work but only for 2 level depth:

import numpy as np


def is_in(arr, values):
    agg = []
    for a in arr:
        if isinstance(a, list):
            result = is_in(a, values)
            agg.append(result)
        else:
            result = np.isin(arr, values)
            return result
    return agg

arr = np.array([[0, 50], [100, 150], [200, 250]])
values = [100, 200, 300]

print(is_in(arr, values))

Comments

-3

also change name of that variable from values to something different to valuess for example.

if valuess in arr.values :
print(valuess)

OR

Use a lambda function.

Let's say you have an array:

nums = [0,1,5]
Check whether 5 is in nums:

(len(filter (lambda x : x == 5, nums)) > 0)

1 Comment

why change the variable name? Also, how does this answer the question..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.