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


data = np.random.randn(7, 3)

data
[1]:
array([[-0.50687148, -0.92123541, -1.33470444],
       [-0.47316782, -0.05354427,  0.3144167 ],
       [-0.51270165, -1.30401598, -0.9362869 ],
       [-0.19429791,  1.12032183,  0.19184738],
       [ 0.07609175,  1.75052865, -1.27389361],
       [ 1.03374626, -0.29737004,  0.0944219 ],
       [ 0.82837672, -0.29511481, -0.25849806]])
[2]:
data.sort(0)

data
[2]:
array([[-0.51270165, -1.30401598, -1.33470444],
       [-0.50687148, -0.92123541, -1.27389361],
       [-0.47316782, -0.29737004, -0.9362869 ],
       [-0.19429791, -0.29511481, -0.25849806],
       [ 0.07609175, -0.05354427,  0.0944219 ],
       [ 0.82837672,  1.12032183,  0.19184738],
       [ 1.03374626,  1.75052865,  0.3144167 ]])

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([[-1.33470444, -1.30401598, -0.51270165],
       [-1.27389361, -0.92123541, -0.50687148],
       [-0.9362869 , -0.47316782, -0.29737004],
       [-0.29511481, -0.25849806, -0.19429791],
       [-0.05354427,  0.07609175,  0.0944219 ],
       [ 0.19184738,  0.82837672,  1.12032183],
       [ 0.3144167 ,  1.03374626,  1.75052865]])
[4]:
data
[4]:
array([[-0.51270165, -1.30401598, -1.33470444],
       [-0.50687148, -0.92123541, -1.27389361],
       [-0.47316782, -0.29737004, -0.9362869 ],
       [-0.19429791, -0.29511481, -0.25849806],
       [ 0.07609175, -0.05354427,  0.0944219 ],
       [ 0.82837672,  1.12032183,  0.19184738],
       [ 1.03374626,  1.75052865,  0.3144167 ]])