Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort 2d numpy array lexicographically

I have a large 2d array with hundreds of columns. I would like to sort it lexicographically, i.e. by first column, then by second column, and so on until the last column. I imagine this should be easy to do but I haven't been able to find a quick way to do this.

like image 448
grigor Avatar asked Jul 09 '16 00:07

grigor


People also ask

How do you sort a 2D NumPy array in Python?

Sorting 2D Numpy Array by column at index 1 Select the column at index 1 from 2D numpy array i.e. It returns the values at 2nd column i.e. column at index position 1 i.e. Now get the array of indices that sort this column i.e. It returns the index positions that can sort the above column i.e.

How do you sort an array Lexicographically?

Java Program to Sort Elements in Lexicographical Order (Dictionary Order) Sorting a string array in Lexicographical Order (Dictionary Order) using two approaches: By using any sorting technique to sort array elements. By using sort() function present in Arrays class in util package in java.

Can you sort a 2D array in Python?

To sort a two-dimensional list in Python use the sort() list method, which mutates the list, or the sorted() function, which does not. Set the key parameter for both types using a lambda function and return a tuple of the columns to sort according to the required sort order.


1 Answers

This is what numpy.lexsort is for, but the interface is awkward. Pass it a 2D array, and it will argsort the columns, sorting by the last row first, then the second-to-last row, continuing up to the first row:

>>> x
array([[0, 0, 0, 2, 3],
       [2, 3, 2, 3, 2],
       [3, 1, 3, 0, 0],
       [3, 1, 1, 3, 1]])
>>> numpy.lexsort(x)
array([4, 1, 2, 3, 0], dtype=int64)

If you want to sort by rows, with the first column as the primary key, you need to rotate the array before lexsorting it:

>>> x[numpy.lexsort(numpy.rot90(x))]
array([[0, 0, 0, 2, 3],
       [2, 3, 2, 3, 2],
       [3, 1, 1, 3, 1],
       [3, 1, 3, 0, 0]])
like image 102
user2357112 supports Monica Avatar answered Nov 09 '22 04:11

user2357112 supports Monica