Sorting elements of nd arrays
- We can sort elements of nd array.
- Numpy module contains sort() function.
- The default sorting algorithm is quicksort and it is Ascending order.
- We can also specify mergesort, heapsort etc.
- For numbers–>Ascending order.
- For Strings–>alphabetical order.
Example
Python
import numpy as np
help(np.sort)
Output
PowerShell
Help on function sort in module numpy:
sort(a, axis=-1, kind=None, order=None)
Return a sorted copy of an array.
1-D arrays
Example
Python
# 1-D arrays
a = np.array([70,20,60,10,50,40,30])
sorted_array = np.sort(a)
print(f"Original array a : {a}")
print(f"Sorted array(Ascending by default) : {sorted_array}")
Output
PowerShell
Original array a : [70 20 60 10 50 40 30]
Sorted array(Ascending by default) : [10 20 30 40 50 60 70]
Example
Python
# Descending the 1-D arrays
# 1st way :: np.sort(a)[::-1]
a = np.array([70,20,60,10,50,40,30])
sorted_array = np.sort(a)[::-1]
Output
PowerShell
Original array a : ['cat' 'rat' 'bat' 'vat' 'dog']
Sorted array(Ascending) : ['bat' 'cat' 'dog' 'rat' 'vat']
Sorted array(Descending) : ['vat' 'rat' 'dog' 'cat' 'bat']
2-D arrays
- axis-0 —>the number of rows (axis = -2).
- axis-1—>the number of columns (axis= -1) ==> defautl value.
- sorting is based on columns in 2-D arrays by default. Every 1-D array will be sorted.
Example
Python
a= np.array([[40,20,70],[30,20,60],[70,90,80]])
ascending = np.sort(a)
print(f"Original array a :\n {a}")
print(f"Sorted array(Ascending) : \n {ascending}")
Output
PowerShell
Original array a :
[[40 20 70]
[30 20 60]
[70 90 80]]
Sorted array(Ascending) :
[[20 40 70]
[20 30 60]
[70 80 90]]
order parameter
- Use the order keyword to specify a field to use when sorting a structured array:
Example
Python
# creating the structured array
dtype = [('name', 'S10'), ('height', float), ('age', int)]
values = [('Gopie', 1.7, 45), ('Vikranth', 1.5, 38),('Sathwik', 1.8, 28)]
a = np.array(values, dtype=dtype)
sort_height = np.sort(a, order='height')
sort_age = np.sort(a,order='age')
print(f"Original Array :\n {a}")
print(f"Sorting based on height :\n {sort_height}")
print(f"Sorting based on age :\n {sort_age}")
Output
PowerShell
output nhi h