How To Sort A Numpy Array?
Table Of Contents:
- np.sort( )
- Examples Of Sorting Numpy Array.
(1) np.sort( )
- Return a sorted copy of an array.
Syntax:
numpy.sort(a, axis=-1, kind=None, order=None)
Parameters:
- a: array_like – Array to be sorted.
- axis: int or None, optional – Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis.
- kind: {‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}, optional – Sorting algorithm. The default is ‘quicksort’.
- order: str or list of str, optional – When a is an array with fields defined, this argument specifies which fields to compare first, second, etc. A single field can be specified as a string, and not all fields need be specified, but unspecified fields will still be used, in the order in which they come up in the dtype, to break ties.
Return:
- sorted_array: ndarray – Array of the same type and shape as a.
(2) Examples Of Sorting Numpy Array
Example-1: Sorting 1 Dimensional Array
a = np.array([3,1,5,2,6,3,7,4,1])
np.sort(a)
Output:
array([1, 1, 2, 3, 3, 4, 5, 6, 7])
Example-2 : Sort Along The Row
a = np.array([[1,4],[3,2]])
np.sort(a, axis=1)
Output:
array([[1, 4],
[2, 3]])
Example-3 : Sort Along The Column
a = np.array([[1,4],[3,2]])
np.sort(a, axis=0)
Output:
array([[1, 2],
[3, 4]])
Example-4 : Sorting with ‘axis = None’
a = np.array([[1,4],[3,2]])
np.sort(a, axis=None)
Output:
array([1, 2, 3, 4])
Note:
- If You Put axis = None
- It will sort the flattened array.