ndarray的每一行中的N个最大值 [英] N largest values in each row of ndarray
本文介绍了ndarray的每一行中的N个最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个ndarray,其中每一行都是一个单独的直方图.对于每一行,我希望找到前N个值.
I have an ndarray where each row is a separate histogram. For each row, I wish to find the top N values.
I am aware of a solution for the global top N values (A fast way to find the largest N elements in an numpy array), but I don't see how to get the top N for each row.
我可以遍历每一行并应用一维解决方案,但是我不应该能够通过numpy广播做到这一点吗?
I could iterate over each row and apply the 1D solution, but shouldn't I be able to do this with numpy broadcasting?
推荐答案
您可以使用与链接的问题相同的方式使用np.partition
:排序已经沿最后一个轴进行了:
You can use np.partition
in the same way as the question you linked: the sorting is already along the last axis:
In [2]: array([[ 5, 4, 3, 2, 1],
[10, 9, 8, 7, 6]])
In [3]: b = np.partition(a, 3) # top 3 values from each row
In [4]: b[:,-3:]
Out[4]:
array([[ 3, 4, 5],
[ 8, 9, 10]])
这篇关于ndarray的每一行中的N个最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文