Sorting using np.sort( ) :
The sort( ) function returns a sorted copy of the array.
Python
import numpy as np arr = np.array([30, 10, 40, 20]) sorted_arr = np.sort(arr) print(sorted_arr) #output [10 20 30 40] Python
import numpy as np arr = np.array([30, 10, 40, 20]) desc = np.sort(arr)[::-1] print(desc) #output [40 30 20 10] Sorting 2D Arrays :
By default, sorting happens row-wise ( axis = 1 )
Python
import numpy as np arr = np.array([[3, 1, 2], [6, 5, 4]]) print(np.sort(arr)) #output [[1 2 3] [4 5 6]] Use axis = 0 to sort columns.
Python
import numpy as np arr = np.array([30, 10, 40, 20]) print(np.sort(arr, axis=0)) #output [[3 1 2] [6 5 4]] Sorting using ndarray.sort( ) :
This method sorts the array in-place.
Python
import numpy as np arr = np.array([30, 10, 40, 20]) arr.sort() print(arr) #output [10 20 30 40]