1

I want to check if any value in the array is greater than a certain threshold,.... do something

But it seems the if loop in the following code does not work. It does not print 'yes' in the if loop even the conditions were satisfied. Any idea why?

import random
import numpy as np

data = []
for i in range(0,10):
    val = random.randint(0,110)
    data.append(val)

data_np = np.array(data)


if all(i>=100 for i in data_np):
    print('yes')

print(data_np)
1
  • 5
    You write I want to check if **any** value [...], but in your code you use all() instead of any() in your check. Commented Sep 12, 2022 at 10:21

3 Answers 3

2
import numpy as np 

arr = np.random.randint(0,30,10)
threshold = 20
mask = arr > threshold
print("arr", arr)

if True in mask:
    print("yes, elements above threshold are :", arr[mask])
else:
    print("No elements are above threshold")
Sign up to request clarification or add additional context in comments.

Comments

2

For a numpy array, use the .any method on a mask instead of looping through the array:

data_np = np.random.randint(0, 110, 10)
if (data_np >= 100).any():
    print('yes')

Comments

0

replace all to any.

if any(i>=100 for i in data_np):

more information : you want to know any number not all numbers is greater or not. so you should use ,any, founction instead of ,all,.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.