numpy.sort() is used to sort the elements of a NumPy array. It returns a sorted copy of the array while leaving the original array unchanged. Sorting can be performed on 1D arrays as well as along specific axes of multi-dimensional arrays.
Example: The following example sorts the elements of a 1D array in ascending order.
import numpy as np
a = np.array([8, 3, 6, 1, 5])
r = np.sort(a)
print(r)
Output
[1 3 5 6 8]
Explanation: np.sort(a) returns a new array with the elements arranged in ascending order.
Syntax
numpy.sort(a, axis=-1, kind=None, order=None)
Parameters:
- a: Input array to be sorted.
- axis (optional): Axis along which sorting is performed. -1 -> Sort along the last axis (default), 0 -> Sort along columns, 1 -> Sort along rows and None -> Flatten the array before sorting.
- kind (optional): Sorting algorithm to use ('quicksort', 'mergesort', 'heapsort', 'stable').
- order (optional): Field name(s) used when sorting structured arrays.
Return Value: Returns a sorted copy of the input array.
Examples
Example 1: In this example, a 2D array is sorted column-wise. Each column is sorted independently from top to bottom.
import numpy as np
a = np.array([ [12, 5],
[3, 18],
[8, 2] ])
r = np.sort(a, axis=0)
print(r)
Output
[[ 3 2] [ 8 5] [12 18]]
Explanation: np.sort(a, axis=0) sorts the values within each column while keeping the column structure unchanged.
Example 2: The following example sorts each row of a 2D array independently.
import numpy as np
a = np.array([ [9, 4, 7],
[2, 8, 1] ])
r = np.sort(a, axis=1)
print(r)
Output
[[4 7 9] [1 2 8]]
Explanation: np.sort(a, axis=1) sorts the elements within each row from left to right.
Example 3: This example sorts all elements of a 2D array together by first flattening the array.
import numpy as np
a = np.array([ [15, 4],
[9, 1] ])
r = np.sort(a, axis=None)
print(r)
Output
[ 1 4 9 15]
Explanation: axis=None flattens the array into a single dimension before sorting all elements in ascending order.