且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 numpy 矩阵中找到第 n 个最大值的最快方法

更新时间:2022-11-14 10:14:51

您可以展平矩阵,然后对其进行排序:

>>>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]96

There 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