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.
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.
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.
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.
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 lexsort
ing 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]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With