How to sort Numpy array in Python – Various Ways?

Hello everyone, in this tutorial, we will learn how to create the numpy arrays and various ways to sort numpy array in Python. Please go through this tutorial carefully for better understanding and further implementation of the numpy module.

DefinitionNumpy is a package in python which stands for ‘Numerical Python’. It is useful for scientific computing and data science.

Numpy Array

It is simply a collection of elements, indexed by a positive integer having the same data type.

Creating a numpy array:

import numpy as np
x=np.array([1,2,9,10,4])
print(x)
Output: [1,2,9,10,4]

Sorting Numpy Array in Python

There are various ways to sort the numpy array.

  • Sorting a 1-D array
  • Sorting a numpy array by rows and columns.
  • Sorting in reverse order.

Sorting a 1-D array

We can sort 1-D numpy array with the help of np.sort function. It simply takes an array object as an argument.

import numpy as np
s=np.array([5,4,3,1,6])
print(np.sort(s))
Output:
[1,3,4,5,6]

Sorting a numpy array by rows and columns

We can a numpy array by rows and columns. It is implemented on n-D array. Here we are taking an example of a 2-D array.

Here np.sort will take two arguments:

  1. Array object.
  2. Axis ( 0 for column and 1 for row ).

Example:

Sorting along column – numpy array

import numpy as np
x=np.array([4,3,5,2,12],[1,2,3,5,4],[4,1,2,9,5])
print(np.sort(x,axis=0))               #column
Output:
[[1,1,2,2,4]
 [4,2,3,5,5]
 [4,3,5,9,12]]

 

Sorting along row

import numpy as np
x=np.array([4,3,5,2,12],[1,2,3,5,4],[4,1,2,9,5])
print(np.sort(x,axis=1))               #row
Output:
[[2,3,4,5,12]
 [1,2,3,4,5]
 [1,2,4,5,9]]

Sorting in Reverse Order

It is simply sorting a 1-D array in descending order. To sort numpy array in descending order, we have to use np.sort on the negative values in the array.

import numpy as np
x=np.array([5,3,2,1,4)
print(abs(np.sort(-x)))               #descending order
Output:
[5,4,3,2,1]

You can also do a similar case for sorting along columns and rows in descending order.

 

There are various approaches to the same but I have given you the simplest approach and ways to sort numpy array.

I hope you would be benefited with this tutorial.

 

You can also read more about Mathematical Functions in Numpy

Leave a Reply

Your email address will not be published. Required fields are marked *