Sorting a python array/recarray by column

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

I have a fairly simple question about how to sort an entire array/recarray by a given column. For example, given the array:

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

I would like to sort data by the first column to return:

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

回答1:

Use data[np.argsort(data[:, 0])] where the 0 is the column index on which to sort:

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


回答2:

you are looking for 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)] 

i.e.

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


回答3:

This is somewhat tricky:

data[data[:,0].argsort()]  # data[:,n] -- get entire column of index n # argsort() -- get the indices that would sort it # data[data[:,n].argsort()] -- get data array sorted by n-th column 

I found this recipe here:

http://www.scipy.org/NumPy_for_Matlab_Users

http://mathesaurus.sourceforge.net/matlab-numpy.html



回答4:

To sort on the second column use 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]] >>>  


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!