Finding index by iterating over each row of matrix

前端 未结 1 1758
一个人的身影
一个人的身影 2021-01-24 16:20

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         


        
相关标签:
1条回答
  • 2021-01-24 16:38

    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.

    0 讨论(0)
提交回复
热议问题