Sorting NumPy Arrays with Algorithms

NumPyNumPyBeginner
Practice Now

Introduction

Sorting is a process where elements of an array are arranged in an ordered sequence based on the given criteria. In the NumPy library, there are various functions available that perform sorting operations based on different sorting algorithms such as quicksort, heapsort, and mergesort. In this lab, we will learn how to sort ndarrays in NumPy using different sorting algorithms.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.

Import NumPy Library

In this step, we will import NumPy library, which is required to perform the sorting operations.

import numpy as np

Sort Along Axis

In this step, we will sort elements of an array based on a particular axis. To sort an array, we will use the sort() function of NumPy.

a = np.array([[17, 15], [10, 25]])
arr1 = np.sort(a, axis = 0)
print("Sorting Along first axis : \n")
print(arr1)

Sort Along Last Axis

In this step, we will sort an array based on the last axis.

b = np.array([[1, 15], [20, 18]])
arr2 = np.sort(b, axis = -1)
print("\nSorting along last axis : \n")
print(arr2)

Sort Along None Axis

In this step, we will sort elements of an array along none axis, where the array is flattened before sorting.

c = np.array([[12, 15], [10, 1]])
arr3 = np.sort(c, axis = None)
print("\nSorting Along none axis : \n")
print(arr3)

Sort an Array Using Fields

In this step, we will sort an array using fields.

d = np.dtype([('name', 'S10'),('marks',int)])
arr = np.array([('Mukesh',200),('John',251)],dtype = d)
print("Sorting data ordered by name")
print(np.sort(arr,order = 'name'))

Summary

In this lab, we learned about sorting in NumPy library. We also learned about numpy.sort() function and its syntax, parameters, and returned values. By using different parameters of numpy.sort() function, we sorted elements of an array along different axes and fields.

Other NumPy Tutorials you may like