Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a python array/recarray by column

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]]) 
like image 404
mike Avatar asked Jul 26 '11 19:07

mike


People also ask

How do you arrange an array in ascending order in Python?

Python List sort() - Sorts Ascending or Descending List. The list. sort() method sorts the elements of a list in ascending or descending order using the default < comparisons operator between items. Use the key parameter to pass the function name to be used for comparison instead of the default < operator.

Can you sort NumPy array?

The NumPy ndarray object has a function called sort() , that will sort a specified array.


1 Answers

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]]) 
like image 130
NPE Avatar answered Sep 26 '22 14:09

NPE