I have an numpy array \'A\' of size 5000x10
. I also have another number \'Num\'
. I want to apply the following to each row of A:
import
You could use argmax
-
A.shape[1] - 1 - (Num > A)[:,::-1].argmax(1)
Alternatively with cumsum
and argmax
-
(Num > A).cumsum(1).argmax(1)
Explanation : With np.max(np.where(..)
, we are basically looking to get the last occurrence of matches along each row on the comparison.
For the same, we can use argmax
. But, argmax
on a boolean array gives us the first occurrence and not the last one. So, one trick is to perform the comparison and flip the columns with [:,::-1]
and then use argmax
. The column indices are then subtracted by the number of cols in the array to make it trace back to the original order.
On the second approach, it's very similar to a related post and therefore quoting from it :
One of the uses of argmax is to get ID of the first occurence of the max element along an axis in an array . So, we get the cumsum along the rows and get the first max ID, which represents the last non-zero elem. This is because cumsum on the leftover elements won't increase the sum value after that last non-zero element.