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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33181350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:57:36  来源:igfitidea点击:

Quickest way to find the nth largest value in a numpy Matrix

pythonnumpy

提问by thefoxrocks

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?

您可以使用k.max(),但当然这只会返回最高值135。如果我想要第二个或第三个怎么办?

采纳答案by rofls

You can flattenthe 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

回答by serv-inc

As said, np.partitionshould be faster (at most O(n) running time):

至于np.partition应该快了(最多O(n)的运行时间):

np.partition(k.flatten(), -2)[-2]

should return the 2nd largest element. (partitionguarantees that the numbered element is in position, all elements before are smaller, and all behind are bigger).

应该返回第二大元素。(partition保证编号的元素就位,前面的所有元素都较小,后面的所有元素都较大)。

回答by Lakshay Chawla

import numpy as np
a=np.array([[1,2,3],[4,5,6]])
a=a.reshape((a.shape[0])*(a.shape[1]))  # n is the nth largest taken by us
print(a[np.argsort()[-n]])

回答by drsealks

Another way of doing this when repeating elements are presented in the array at hand. If we have something like

当重复元素出现在手头的数组中时,另一种方法是这样做。如果我们有类似的东西

a = np.array([[1,1],[3,4]])

then the second largest element will be 3, not 1.

那么第二大元素将是 3,而不是 1。

Alternatively, one could use the following snippet:

或者,可以使用以下代码段:

second_largest = sorted(list(set(a.flatten().tolist())))[-2]

First, flatten matrix, then only leave unique elements, then back to the mutable list, sort it and take the second element. This should return the second largest element from the end even if there are repeating elements in the array.

首先,展平矩阵,然后只留下唯一元素,然后回到可变列表,对其进行排序并取第二个元素。即使数组中有重复元素,这也应该从末尾返回第二大元素。

回答by Luka Tikaradze

nums = [[ 35,  48,  63],
        [ 60,  77,  96],
        [ 91, 112, 135]]

highs = [max(lst) for lst in nums]
highs[nth]

回答by Alberto A

Using the 'unique' function is a very clean way to do it, but likely not the fastest:

使用 'unique' 函数是一种非常干净的方法,但可能不是最快的:

k = array([[ 35,  48,  63],
           [ 60,  77,  96],
           [ 91, 112, 135]])
i = numpy.unique(k)[-2]

for the second largest

为第二大