Discuss how the sort function can be applied on NumPy arrays in Python?

PythonServer Side ProgrammingProgramming

NumPy refers to ‘Numerical’ ‘Python’. It is a library that contains multidimensional array objects and multiple methods that help in processing the arrays. NumPy can be used to perform a wide variety of operations on arrays. It is used in conjunction with packages like SciPy, Matplotlib and so on. NumPy+Matplotlib can be understood as an alternative to MatLab. It is an open source package, which means it can be used by anyone.

The most important object present in NumPy package is an n-dimensional array which is known as ‘ndarray’. It defines the collection of items of the same type. These values inside the ndarray can be accessed using indexing (0-based index). Every item in the ndarray takes the same size of block in the memory space. Every element’s type in the ndarray can be found using the ‘dtype’ function.

An item from the ndarray can be extracted using array slicing. It is represented as an object of array scalar type. A variety of sorting functions are present in NumPy. They can be implemented in different methods, and each of these functions differ based on their execution speed, the worst case performance, memory required, and so on.

The ‘sort’ function in NumPy returns a sorted copy of the array which is passed as input to it.

numpy.sort(arr, axis, kind, order)

Here, ‘arr’ is the array that needs to be sorted. The ‘axis’ refers to the axis along which the array is to be sorted. The ‘kind’ refers to the type of sorting, default value being quicksort. If the array contains any other fields, ‘order’ refers to these fields that need to be sorted.

Here’s the example to apply sort() on NumPy arrays −

Example

 Live Demo

import numpy as np
my_arr = np.array([[3,56],[19,100]])
print("Original array is :")
print(my_arr)
print("The sort() function called")
print(np.sort(my_arr))
print("Sorting array along axis 0")
print(np.sort(my_arr, axis = 0))
dt = np.dtype([('Name', 'S6'),('Age', int)])
my_arr = np.array([("Will",20),("Jack",19),("Bob", 23)], dtype = dt)
print("Original array is :")
print(my_arr)
print("Array sorted by name ")
print(np.sort(my_arr, order = 'Name'))

Output

Original array is :
[[ 3 56]
[ 19 100]]
The sort() function called
[[ 3 56]
[ 19 100]]
Sorting array along axis 0
[[ 3 56]
[ 19 100]]
Original array is :
[(b'Will', 20) (b'Jack', 19) (b'Bob', 23)]
Array sorted by name
[(b'Bob', 23) (b'Jack', 19) (b'Will', 20)]

Explanation

  • The required libraries are imported into the environment.
  • The ndarray is created, and it is sorted using the ‘sort’ function.
  • The output is displayed.
  • Again, it is sorted along the axis 0 and output is displayed on the console.
  • Another array consisting of name and age is created, and it is sorted along the axis 0.
  • Output is displayed on the console.
raja
Published on 10-Dec-2020 13:17:58
Advertisements