Sorting a python array/recarray by column Sorting a python array/recarray by column numpy numpy

Sorting a python array/recarray by column


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

In [27]: import numpy as npIn [28]: data = np.array([[5,2], [4,1], [3,6]])In [29]: col = 0In [30]: data=data[np.argsort(data[:,col])]Out[30]: array([[3, 6],       [4, 1],       [5, 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]: aOut[7]: [[5, 2], [4, 1], [3, 6]]In [8]: sorted(a, key=operator.itemgetter(0))Out[8]: [[3, 6], [4, 1], [5, 2]]


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