bundles / numpy latest / numpy / lexsort
_ArrayFunctionDispatcher
numpy:lexsort
Signature
def lexsort ( keys , axis = -1 ) Summary
Perform an indirect stable sort using a sequence of keys.
Extended Summary
Given multiple sorting keys, lexsort returns an array of integer indices that describes the sort order by multiple keys. The last key in the sequence is used for the primary sort order, ties are broken by the second-to-last key, and so on.
Parameters
keys: (k, m, n, ...) array-likeThe
kkeys to be sorted. The last key (e.g, the last row ifkeysis a 2D array) is the primary sort key. Each element ofkeysalong the zeroth axis must be an array-like object of the same shape.axis: int, optionalAxis to be indirectly sorted. By default, sort over the last axis of each sequence. Separate slices along
axissorted over independently; see last example.
Returns
indices: (m, n, ...) ndarray of intsArray of indices that sort the keys along the specified axis.
Examples
Sort names: first by surname, then by name.import numpy as np surnames = ('Hertz', 'Galilei', 'Hertz') first_names = ('Heinrich', 'Galileo', 'Gustav') ind = np.lexsort((first_names, surnames)) ind✓
[surnames[i] + ", " + first_names[i] for i in ind]
✓a = [1, 5, 1, 4, 3, 4, 4] # First sequence b = [9, 4, 0, 4, 0, 2, 1] # Second sequence ind = np.lexsort((b, a)) # Sort by `a`, then by `b` ind [(a[i], b[i]) for i in ind]✓
np.argsort((b, a), kind='stable')
✓x = np.array([(ai, bi) for ai, bi in zip(a, b)], dtype = np.dtype([('x', int), ('y', int)])) np.argsort(x) # or np.argsort(x, order=('x', 'y'))✓
arr = np.asarray([b, a]) ind2 = np.lexsort(arr) np.testing.assert_equal(ind2, ind)✓
np.testing.assert_equal(np.lexsort(arr, axis=0), np.lexsort(arr, axis=-1))✓
x = [[1, 2, 3, 4], [4, 3, 2, 1], [2, 1, 4, 3]] y = [[2, 2, 1, 1], [1, 2, 1, 2], [1, 1, 2, 1]] np.lexsort((x, y), axis=1)✓
for i in range(3): print(np.lexsort((x[i], y[i])))✓
See also
- argsort
Indirect sort.
- ndarray.sort
In-place sort.
- sort
Return a sorted copy of an array.
Aliases
-
numpy.lexsort