简体   繁体   中英

Finding index by iterating over each row of matrix

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 numpy as np
np.max(np.where(Num > A[0,:]))

Is there a pythonic way than writing a for loop for above.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM