2015-10-17 96 views
5

有很多解决方案,为单个阵列做到这一点的,但对于一个矩阵,如:最快的方式

>>> k 
array([[ 35, 48, 63], 
     [ 60, 77, 96], 
     [ 91, 112, 135]]) 

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

+2

看看这个答案:http://stackoverflow.com/questions/26603747/get-the-indices-of-n-highest-values-in-an-ndarray – NJM

回答

8

可以flatten矩阵,然后对其进行排序:

>>> 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 
+4

'np.partition'可能会更快 - 它进行了部分排序,只是将数组分成两部分。 – hpaulj

+0

哦,我喜欢那样。 – rofls

+0

这种方法可能会更好,如果他想抓住多个元素,比如说第二,第三大等等,因为除索引之外,它们都将不再进行其他操作。 – rofls

6

由于saidnp.partition应该更快(最多O(n)的运行时间):

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

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

0
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]]) 
+2

感谢您的贡献。如果你解释你的想法,你的答案可能会更有用。 –