# numpy.lexsort¶

numpy.lexsort(keys, axis=-1)

Perform an indirect sort using a list of keys.

Imagine three input keys, a, b and c. These can be seen as columns in a spreadsheet. The first row of the spreadsheet would therefore be a[0], b[0], c[0]. Lexical sorting orders the different rows by first sorting on the on first column (key), then the second, and so forth. At each step, the previous ordering is preserved when equal keys are encountered.

Parameters: keys : (k,N) array or tuple containing k (N,)-shaped sequences The k different “columns” to be sorted. The last column is the primary sort column. axis : int, optional Axis to be indirectly sorted. By default, sort over the last axis. indices : (N,) ndarray of ints Array of indices that sort the keys along the specified axis.

See also

argsort
Indirect sort.
ndarray.sort
In-place sort.
sort
Return a sorted copy of an array.

Examples

Sort names: first by surname, then by name.

```>>> surnames =    ('Hertz',    'Galilei', 'Hertz')
>>> first_names = ('Heinrich', 'Galileo', 'Gustav')
>>> ind = np.lexsort((first_names, surnames))
>>> ind
array([1, 2, 0])
```
```>>> [surnames[i] + ", " + first_names[i] for i in ind]
['Galilei, Galileo', 'Hertz, Gustav', 'Hertz, Heinrich']
```

Sort two columns of numbers:

```>>> a = [1,5,1,4,3,4,4] # First column
>>> b = [9,4,0,4,0,2,1] # Second column
>>> ind = np.lexsort((b,a)) # Sort by second, then first column
>>> print ind
[2 0 4 6 5 3 1]
```
```>>> [(a[i],b[i]) for i in ind]
[(1, 0), (1, 9), (3, 0), (4, 1), (4, 2), (4, 4), (5, 4)]
```

Note that the first elements are sorted. For each first element, the second elements are also sorted.

A normal argsort would have yielded:

```>>> [(a[i],b[i]) for i in np.argsort(a)]
[(1, 9), (1, 0), (3, 0), (4, 4), (4, 2), (4, 1), (5, 4)]
```

Structured arrays are sorted lexically:

```>>> x = np.array([(1,9), (5,4), (1,0), (4,4), (3,0), (4,2), (4,1)],
...              dtype=np.dtype([('x', int), ('y', int)]))
```
```>>> np.argsort(x) # or np.argsort(x, order=('x', 'y'))
array([2, 0, 4, 6, 5, 3, 1])
```

numpy.sort

numpy.argsort