在 numpy 矩阵中找到第 n 个最大值的最快方法 [英] Quickest way to find the nth largest value in a numpy Matrix
本文介绍了在 numpy 矩阵中找到第 n 个最大值的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于单个数组有很多解决方案可以做到这一点,但是对于矩阵呢,例如:
<预><代码>>>>克数组([[ 35, 48, 63],[ 60, 77, 96],[ 91, 112, 135]])您可以使用k.max()
,但当然这只会返回最高值,135
.如果我想要第二个或第三个怎么办?
解决方案
您可以展平矩阵,然后对其进行排序:
<预><代码>>>>k = np.array([[ 35, 48, 63],... [ 60, 77, 96],... [ 91, 112, 135]])>>>flat=k.flatten()>>>平面排序()>>>平坦的数组([ 35, 48, 60, 63, 77, 91, 96, 112, 135])>>>平[-2]112>>>平[-3]96There are lots of solutions to do this for a single array, but what about a matrix, such as:
>>> k
array([[ 35, 48, 63],
[ 60, 77, 96],
[ 91, 112, 135]])
You can use k.max()
, but of course this only returns the highest value, 135
. What if I want the second or third?
解决方案
You can flatten the matrix and then sort it:
>>> k = np.array([[ 35, 48, 63],
... [ 60, 77, 96],
... [ 91, 112, 135]])
>>> flat=k.flatten()
>>> flat.sort()
>>> flat
array([ 35, 48, 60, 63, 77, 91, 96, 112, 135])
>>> flat[-2]
112
>>> flat[-3]
96
这篇关于在 numpy 矩阵中找到第 n 个最大值的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文