简体   繁体   English

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

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

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 . 你可以使用k.max() ,但当然这只返回最高值135 What if I want the second or third? 如果我想要第二个或第三个怎么办?

As said , np.partition should be faster (at most O(n) running time): 至于np.partition应该更快(最多O(n)的运行时间):

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

should return the 2nd largest element. 应该返回第二大元素。 ( partition guarantees that the numbered element is in position, all elements before are smaller, and all behind are bigger). partition保证编号元素在位,前面的所有元素都更小,后面的所有元素都更大)。

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
nums = [[ 35,  48,  63],
        [ 60,  77,  96],
        [ 91, 112, 135]]

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

Using the 'unique' function is a very clean way to do it, but likely not the fastest: 使用“独特”功能是一种非常干净的方法,但可能不是最快的:

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

for the second largest 为第二大

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

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. 即使数组中有重复元素,这也应该从结尾返回第二大元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM