Finding index by iterating over each row of matrix

房东的猫 提交于 2019-12-20 04:19:36

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/40009008/finding-index-by-iterating-over-each-row-of-matrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!