In some cases, we require a sorted array for computation. For this purpose, the numpy module of Python provides a function called numpy.sort(). This function gives a sorted copy of the source array or input array.
numpy.sort(a, axis=-1, kind='quicksort', order=None)
x: array_like
This parameter defines the source array, which is going to be sorted.
axis: int or None(optional)
This parameter defines the axis along which the sorting is performed. If this parameter is None, the array will be flattened before sorting, and by default, this parameter is set to -1, which sorts the array along the last axis.
kind: {quicksort, heapsort, mergesort}(optional)
This parameter is used to define the sorting algorithm, and by default, the sorting is performed using 'quicksort'.
order: str or list of str(optional)
When an array is defined with fields, its order defines the fields for making a comparison in first, second, etc. Only the single field can be specified as a string, and not necessarily for all fields. However, the unspecified fields will still be used, in the order in which they come up in the dtype, to break the ties.
This function returns a sorted copy of the source array, which will have the same shape and type as a source array.
import numpy as np x=np.array([[1,4,2,3],[9,13,61,1],[43,24,88,22]]) x y=np.sort(x) y
Output:
In the above code
In the output, it shows a sorted copy of the source array of the same type and shape.
import numpy as np x=np.array([[1,4,2,3],[9,13,61,1],[43,24,88,22]]) x y=np.sort(x, axis=None) y
Output:
import numpy as np x=np.array([[1,4,2,3],[9,13,61,1],[43,24,88,22]]) x y=np.sort(x,axis=0) y z=np.sort(x,axis=1) z
Output:
import numpy as np dtype = [('name', 'S10'), ('height', float), ('age', int),('gender','S10')] values = [('Shubham', 5.9, 23, 'M'), ('Arpita', 5.6, 23, 'F'),('Vaishali', 5.2, 30, 'F')] x=np.array(values, dtype=dtype) x y=np.sort(x, order='age') y z=np.sort(x, order=['age','height']) z
Output:
In the above code
In the output, it shows a sorted copy of the structured array with a defined order.