Sorting¶
In [1]:
%pip install numpy
import numpy as np
Requirement already satisfied: numpy in /home/samrat/Documents/numpy-torch-tutorials/venv/lib/python3.8/site-packages (1.24.4) Note: you may need to restart the kernel to use updated packages.
In [3]:
foo = np.array([1,7,3,9,0,9,1])
np.sort(foo)
Out[3]:
array([0, 1, 1, 3, 7, 9, 9])
In [5]:
foo.sort()
foo
Out[5]:
array([0, 1, 1, 3, 7, 9, 9])
In [7]:
bar = np.array([5, np.nan, 3, 11])
np.sort(bar)
Out[7]:
array([ 3., 5., 11., nan])
In [8]:
np.sort(bar)[::-1]
Out[8]:
array([nan, 11., 5., 3.])
In [10]:
-np.sort(-bar)
Out[10]:
array([11., 5., 3., nan])
In [12]:
boo = np.random.randint(low=0, high=10, size=(3,3))
boo
Out[12]:
array([[6, 3, 8], [8, 3, 1], [0, 5, 1]])
In [13]:
np.sort(boo, axis=0)
Out[13]:
array([[0, 3, 1], [6, 3, 1], [8, 5, 8]])
In [14]:
np.sort(boo, axis=1)
Out[14]:
array([[3, 6, 8], [1, 3, 8], [0, 1, 5]])
In [15]:
np.sort(boo, axis=-1)
Out[15]:
array([[3, 6, 8], [1, 3, 8], [0, 1, 5]])
In [16]:
boo[np.argsort(boo[:, 0])]
Out[16]:
array([[0, 5, 1], [6, 3, 8], [8, 3, 1]])