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]:
sort an array along a specified axis¶
In [4]:
# sort along the row and return a copy
print(np.sort(arr, axis=0))
In [5]:
# sort along the row in place
arr.sort(axis=0)
print(arr)
In [6]:
# sort along the column and return a copy
print(np.sort(arr, axis=1))
In [7]:
# sort along the column in place
arr.sort(axis=1)
print(arr)
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]:
Order by name¶
In [9]:
np.sort(arr, order = 'name')
Out[9]:
Order by age:¶
In [10]:
np.sort(arr, order = 'age')
Out[10]:
compute the indices that would sort an array along a specified axis¶
In [11]:
arr = np.random.rand(5,5)
arr
Out[11]:
In [12]:
# along the row
print(np.argsort(arr, axis=0))
In [13]:
# along the column
print(np.argsort(arr, axis=1))
In [14]:
# if axis=None, return the indices of a flattened array
print(np.argsort(arr, axis=None))