Sort

As in Python’s list, NumPy arrays can be sorted in-place using the numpy.sort method. You can sort any one-dimensional section of values in a multidimensional array in place along an axis by passing the axis number to sort:

[1]:
import numpy as np


rng = np.random.default_rng()
data = rng.random((7, 3))

data
[1]:
array([[0.7740598 , 0.20912608, 0.17613129],
       [0.2691818 , 0.84813834, 0.6284038 ],
       [0.61870574, 0.86602031, 0.77810677],
       [0.58221564, 0.18867566, 0.61433336],
       [0.19384893, 0.97196918, 0.58002664],
       [0.56652261, 0.968951  , 0.0066615 ],
       [0.56644055, 0.47526286, 0.8142787 ]])
[2]:
data.sort(0)

data
[2]:
array([[0.19384893, 0.18867566, 0.0066615 ],
       [0.2691818 , 0.20912608, 0.17613129],
       [0.56644055, 0.47526286, 0.58002664],
       [0.56652261, 0.84813834, 0.61433336],
       [0.58221564, 0.86602031, 0.6284038 ],
       [0.61870574, 0.968951  , 0.77810677],
       [0.7740598 , 0.97196918, 0.8142787 ]])

np.sort, on the other hand, returns a sorted copy of an array instead of changing the array in place:

[3]:
np.sort(data, axis=1)
[3]:
array([[0.0066615 , 0.18867566, 0.19384893],
       [0.17613129, 0.20912608, 0.2691818 ],
       [0.47526286, 0.56644055, 0.58002664],
       [0.56652261, 0.61433336, 0.84813834],
       [0.58221564, 0.6284038 , 0.86602031],
       [0.61870574, 0.77810677, 0.968951  ],
       [0.7740598 , 0.8142787 , 0.97196918]])
[4]:
data
[4]:
array([[0.19384893, 0.18867566, 0.0066615 ],
       [0.2691818 , 0.20912608, 0.17613129],
       [0.56644055, 0.47526286, 0.58002664],
       [0.56652261, 0.84813834, 0.61433336],
       [0.58221564, 0.86602031, 0.6284038 ],
       [0.61870574, 0.968951  , 0.77810677],
       [0.7740598 , 0.97196918, 0.8142787 ]])