通过遍历矩阵的每一行来查找索引 [英] Finding index by iterating over each row of matrix
问题描述
我有一个大小为5000x10
的numpy数组'A'.我还有另一个号码'Num'
.我想将以下内容应用于A的每一行:
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,:]))
是否有比上面编写for循环更好的pythonic方法.
Is there a pythonic way than writing a for loop for above.
推荐答案
您可以使用argmax
-
A.shape[1] - 1 - (Num > A)[:,::-1].argmax(1)
或者使用cumsum
和argmax
-
(Num > A).cumsum(1).argmax(1)
说明:基本上,我们希望使用np.max(np.where(..)
来获取比较中每一行的最后匹配项.
Explanation : With np.max(np.where(..)
, we are basically looking to get the last occurrence of matches along each row on the comparison.
同样,我们可以使用argmax
.但是,布尔数组上的argmax
给我们第一个出现而不是最后一个出现.因此,一种技巧是执行比较并使用[:,::-1]
翻转列,然后使用argmax
.然后,将列索引减去数组中cols的数量,以使其追溯到原始顺序.
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.
在第二种方法上,它与 related post
非常相似,因此引用了它:
On the second approach, it's very similar to a related post
and therefore quoting from it :
argmax的用途之一是获取max元素在数组中沿轴的第一次出现的ID.因此,我们沿行获得了总和,并获得了第一个最大ID,该ID代表了最后一个非零的elem.这是因为剩余元素的总和不会增加最后一个非零元素之后的总和.
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.
这篇关于通过遍历矩阵的每一行来查找索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!