Breaking News

NumPy Array Sorting

8 – Sort an Array

Sorting of an Array¶

In [2]:
import numpy as np

In [3]:
import numpy as np
arr = np.array([[30,17,15],[19,90,16],[69,53,21]])
arr

Out[3]:
array([[30, 17, 15],
[19, 90, 16],
[69, 53, 21]])

sort an array along a specified axis¶

In [4]:
# sort along the row and return a copy
print(np.sort(arr, axis=0))

[[19 17 15]
[30 53 16]
[69 90 21]]

In [5]:
# sort along the row in place
arr.sort(axis=0)
print(arr)

[[19 17 15]
[30 53 16]
[69 90 21]]

In [6]:
# sort along the column and return a copy
print(np.sort(arr, axis=1))

[[15 17 19]
[16 30 53]
[21 69 90]]

In [7]:
# sort along the column in place
arr.sort(axis=1)
print(arr)

[[15 17 19]
[16 30 53]
[21 69 90]]


Order parameter in sort function¶

In [8]:
dt = np.dtype([('name', 'S10'),('age', int)])
arr = np.array([("Karan",21),("Arpit",25),("Ashish", 17), ("Sam",27),("Robin",22)], dtype = dt)
arr

Out[8]:
array([(b'Karan', 21), (b'Arpit', 25), (b'Ashish', 17), (b'Sam', 27),
(b'Robin', 22)], dtype=[('name', 'S10'), ('age', '<i4')])

Order by name¶

In [9]:
np.sort(arr, order = 'name')

Out[9]:
array([(b'Arpit', 25), (b'Ashish', 17), (b'Karan', 21), (b'Robin', 22),
(b'Sam', 27)], dtype=[('name', 'S10'), ('age', '<i4')])

Order by age:¶

In [10]:
np.sort(arr, order = 'age')

Out[10]:
array([(b'Ashish', 17), (b'Karan', 21), (b'Robin', 22), (b'Arpit', 25),
(b'Sam', 27)], dtype=[('name', 'S10'), ('age', '<i4')])

compute the indices that would sort an array along a specified axis¶

In [11]:
arr = np.random.rand(5,5)
arr

Out[11]:
array([[0.186465  , 0.06569589, 0.81277155, 0.38698898, 0.10392588],
[0.4968922 , 0.54166813, 0.64418867, 0.72097399, 0.51464866],
[0.30127114, 0.76583709, 0.63758779, 0.5547917 , 0.15375515],
[0.05436687, 0.51985718, 0.89521853, 0.01108634, 0.94258898],
[0.21192485, 0.31561459, 0.54977464, 0.41838968, 0.03012578]])
In [12]:
# along the row
print(np.argsort(arr, axis=0))

[[3 0 4 3 4]
[0 4 2 0 0]
[4 3 1 4 2]
[2 1 0 2 1]
[1 2 3 1 3]]

In [13]:
# along the column
print(np.argsort(arr, axis=1))

[[1 4 0 3 2]
[0 4 1 2 3]
[4 0 3 2 1]
[3 0 1 2 4]
[4 0 1 3 2]]

In [14]:
# if axis=None, return the indices of a flattened array
print(np.argsort(arr, axis=None))

[18 24 15  1  4 14  0 20 10 21  3 23  5  9 16  6 22 13 12  7  8 11  2 17
19]