2011-07-26 133 views
24

關於如何按給定列對整個數組/重新排列進行排序,我有一個相當簡單的問題。例如,假設數組:按列排序python數組/重新排列

import numpy as np 
data = np.array([[5,2], [4,1], [3,6]]) 

我想第一列對數據進行排序,返回:

array([[3,6], [4,1], [5,2]]) 

回答

40

使用data[np.argsort(data[:, 0])]其中0是列指數進行排序:

In [27]: import numpy as np 

In [28]: data = np.array([[5,2], [4,1], [3,6]]) 

In [29]: col = 0 

In [30]: data=data[np.argsort(data[:,col])] 
Out[30]: 
array([[3, 6], 
     [4, 1], 
     [5, 2]]) 
10

您正在尋找operator.itemgetter

>>> from operator import itemgetter, attrgetter 

>>> sorted(student_tuples, key=itemgetter(2)) 
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] 

>>> sorted(student_objects, key=attrgetter('age')) 
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] 

In [7]: a 
Out[7]: [[5, 2], [4, 1], [3, 6]] 

In [8]: sorted(a, key=operator.itemgetter(0)) 
Out[8]: [[3, 6], [4, 1], [5, 2]] 
4

排序在第二列中使用itemgetter

>>> from operator import itemgetter 
>>> data = [[5,2], [4,1], [3,6]] 
>>> sorted(data) 
[[3, 6], [4, 1], [5, 2]] 
>>> sorted(data,key=itemgetter(1)) 
[[4, 1], [5, 2], [3, 6]] 
>>>