In the previous article, we saw how we could search for arrays in NumPy using different functions. In this article of today, we are going to see how we can sort different elements in input array by using different built-in functions in NumPy.
To begin with sorting refers means arranging elements in an orderly manner such as alphabetically, numerically, ascending and many more.
Using sort () functions
This is a built-in function in NumPy that returns a copy of the sorted array in order. This array is arranged in sorted format.
Example
import numpy as np
arr = np.array(['e', 'b', 'a', 'c'])
print(np.sort(arr))
NumPy passes the command to the sort function which instructs the compiler to arrange the alphabets in order.
OUTPUT
This function is used when we want the indices of the array, after when it has been sorted.
Example
import numpy as np
arr = np.array([[6,1,3,8,12,2]])
print(np.argsort(arr))
OUTPUT
In the table below, is a list functions with their uses we can use to sort out different arrays.
Arrays of different data-types can be sorted using the sort() functions
Example
Sorting the array of a Boolean expressions
import numpy as np
arr = np.array([True, False, True])
print(np.sort(arr))
NumPy passes the command to the function, which then tells the compiler to sort out given expression.
OUTPUT
When the sort function is used on 2-D array, both the arrays in the given 2-D are sorted
Example
import numpy as np
arr = np.array([['a', 'm', 'd'], ['z', 'f', 'j']])
print(np.sort(arr))
Just like in the example above, the functions are being sorted by the compiler, but in this case the two given arrays are sorted simultaneously.
OUTPUT
There are many other functions used in sorting that were not mention in this article. Sorting is very important in arranging data in a particular order. Hope this article was very interesting. Have a nice day coding.
Comments
Post a Comment
Please do not enter any spam link in the comment box.