Using Python to sort two-dimensional arrays by rows or columns [numpy lexsort] And numpylexsort
 
This example describes how to sort two-dimensional arrays by rows or columns in Python. We will share this with you for your reference. The details are as follows:
 
Lexsort supports sorting arrays by specified rows or columns. It is indirect sorting. lexsort does not modify the original array and returns an index.
 
(Corresponding to the lexsort one-dimensional array isargsort a.argsort()In this way, you can use argsort without modifying the original array and returning the index)
 
By default, elements in the last row are sorted in ascending order, and the index location is returned after the last element is sorted.
 
Set array a and Return Index ind. ind returns a one-dimensional array.
 
For a one-dimensional array, a [ind] is the sorted array.
 
The following is an example of a two-dimensional array.
 
import numpy as np>>> aarray([[ 2, 7, 4, 2],    [35, 9, 1, 5],    [22, 12, 3, 2]])
 
Sort by the order of the last column
 
>>> a[np.lexsort(a.T)]array([[22, 12, 3, 2],    [ 2, 7, 4, 2],    [35, 9, 1, 5]])
 
Sort by last column in reverse order
 
>>>a[np.lexsort(-a.T)]array([[35, 9, 1, 5],    [ 2, 7, 4, 2],    [22, 12, 3, 2]])
 
Sort by the first column
 
>>> a[np.lexsort(a[:,::-1].T)]array([[ 2, 7, 4, 2],    [22, 12, 3, 2],    [35, 9, 1, 5]])
 
Sort by the last line
 
>>> a.T[np.lexsort(a)].Tarray([[ 2, 4, 7, 2],    [ 5, 1, 9, 35],    [ 2, 3, 12, 22]])
 
Sort by the first line
 
>>> a.T[np.lexsort(a[::-1,:])].Tarray([[ 2, 2, 4, 7],    [ 5, 35, 1, 9],    [ 2, 22, 3, 12]])