I have a large 2D numpy array and want to find the indices of the 1D arrays inside it that meet a condition: e.g., have at least a value greater than a given threshold x.
I already can do it the following way but is there a shorter, more efficient way to do it?
import numpy
a = numpy.array([[1,2,3,4,5], [1,2,3,4,20], [1,2,2,4,5]])
indices = []
i = 0
x = 10
for item in a:
if any(j > x for j in item):
indices.append(i)
i += 1
print(indices) # gives [1]
You could use numpy's built-in boolean operations:
import numpy as np
a = np.array([[1,2,3,4,5], [1,2,3,4,20], [1,2,2,4,5]])
indices = np.argwhere(np.any(a > 10, axis=1))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With