Reputation:
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)
Upvotes: 1
Views: 5492
Reputation: 9858
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')
Upvotes: 2
Reputation: 61
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")
Upvotes: 2
Reputation: 109
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,.
Upvotes: 0