Lets take np.array:
array = np.array([[1, 4],
[0, 3],
[2, 3]])
I use this code to find the first element in the first column, where a value is larger than threshold:
index = np.argmax(array[:, 0] > threshold)
Now taken a threshold = 1, I get the index as expected:
>>index = 2
But if I choose a value larger 2, the output is 0. This will mess up my program, because I would like to take the last value and not the first in case no element fulfills the threshold.
Is there an efficient way to get the last value of the array in that case?
EDIT:
I actually don't understand how this should help me here: Numpy: How to find first non-zero value in every column of a numpy array?
I am rather looking for something like making argmax return False
instead of 0.
Comparison of solutions by @Divakar and @Achintha Ihalage
import numpy as np
import time
def first_nonzero(arr, axis, invalid_val=-1):
mask = arr != 0
return np.where(mask.any(axis=axis), mask.argmax(axis=axis), invalid_val)
array = np.random.rand(50000, 50000) * 10
test = array[:, 0]
threshold = 11
t1 = time.time()
index1 = np.argmax(array[:, 0] > threshold) if any(array[:, 0] > threshold) else len(array[:, 0])-1
elapsed1 = time.time() - t1
t2 = time.time()
index2 = first_nonzero(array[:, 0] > threshold, axis=0, invalid_val=len(array[:, 0])-1)
elapsed2 = time.time() - t2
print(index1, "time: ", elapsed1)
print(index2, "time: ", elapsed2)
>>49999 time: 0.012960195541381836
>>49999 time: 0.0009734630584716797
So @Divakar's solution is super fast! Thanks a lot!