In this tutorial, we’ll look at how to sort a numpy array in python along with some of its common use-cases.

## How to sort a numpy array?

You can use the numpy ndarray function `sort()`

to sort a numpy array. It sorts the array in-place. You can also use the global `numpy.sort()`

function which returns a copy of the sorted array. The following is the syntax:

import numpy as np # arr is a numpy ndarray object arr.sort() # or use the gobal numpy.sort() arr_sorted = np.sort(arr)

Here, `arr`

is a numpy array (that is, a numpy ndarray object).

## Examples

Let’s look at some examples and use-cases of sorting a numpy array.

### 1. Sort a 1-D numpy array

We can use the numpy ndarray `sort()`

function to sort a one-dimensional numpy array.

import numpy as np # create a numpy array arr = np.array([4,1,5,2,3]) print(arr) # sort the array arr.sort() print(arr)

Output:

[4 1 5 2 3] [1 2 3 4 5]

In the above example, you can see that numpy array `arr`

gets sorted in-place, that is, the original array gets modified when using the numpy ndarray `sort()`

function.

On the other hand, if you do not want to alter the original array while sorting and would like the sorted array returned as a copy instead, use the global `numpy.sort()`

function. See the example below:

import numpy as np # create a numpy array arr = np.array([4,1,5,2,3]) print(arr) # sort the array arr_sorted = np.sort(arr) print(arr) print(arr_sorted)

Output:

[4 1 5 2 3] [4 1 5 2 3] [1 2 3 4 5]

You can see that the original array `arr`

remains unchanged.

### 2. Customizations in the numpy sort function

The numpy ndarray `sort()`

and the numpy `sort()`

function take additional arguments – `axis`

, `kind`

, and `order`

.

: The axis along which to sort the array. Defaults to -1, that is, sort along the last axis.**axis**: The sorting algorithm to use. The available options are`kind`

`'quicksort'`

,`'mergesort'`

,`'heapsort'`

, and`'stable'`

. The default is`'quicksort'`

.: Used in numpy arrays with defined fields. It determines which fields to compare first.`order`

Let’s look at the result of using different sorting algorithms in the `numpy.sort()`

function.

import numpy as np # create a numpy array arr = np.array([4,1,5,2,3]) print("original array:", arr) # sort the array with different algorithms # quicksort arr_sorted1 = np.sort(arr, kind='quicksort') # mergesort arr_sorted2 = np.sort(arr, kind='mergesort') # heapsort arr_sorted3 = np.sort(arr, kind='heapsort') # stable arr_sorted4 = np.sort(arr, kind='stable') print("quicksort:", arr_sorted1) print("mergesort:", arr_sorted2) print("heapsort:", arr_sorted3) print("stable:", arr_sorted4)

Output:

original array: [4 1 5 2 3] quicksort: [1 2 3 4 5] mergesort: [1 2 3 4 5] heapsort: [1 2 3 4 5] stable: [1 2 3 4 5]

The different sorting algorithms give the same result, what changes is the under the hood operations to determine the order of elements inside the array.

### 3. Sort a numpy array in descending order

You can see that the numpy `sort()`

function doesn’t come which an explicit argument for sorting the array in ascending or descending order. By default, it sorts the array in ascending order. But you can use slicing to reverse the order of a sorted array. See the example below:

import numpy as np # create a numpy array arr = np.array([4,1,5,2,3]) print(arr) # sort the array arr_sorted = np.sort(arr)[::-1] print(arr_sorted)

Output:

[4 1 5 2 3] [5 4 3 2 1]

Here, `np.sort(arr)`

returns a sorted copy of the original array in ascending order which is then reversed using the slicing operator with a -1 step size, `[::-1]`

.

### 4. Sort a 2-D numpy array

You can also sort two-dimensional numpy arrays using the numpy sort function. See the example below.

import numpy as np # create a numpy array arr = np.array([[3,1,2],[7,9,8],[6,5,4]]) print("Original Array") print(arr) # sort the array arr_sorted = np.sort(arr) print("Sorted Array") print(arr_sorted)

Output:

Original Array [[3 1 2] [7 9 8] [6 5 4]] Sorted Array [[1 2 3] [7 8 9] [4 5 6]]

You can see that by default, the `numpy.sort()`

function sorts the array row-wise. That is, in the returned array, we see that the rows are sorted. You can control the sorting axis via the `axis`

parameter which is `-1`

by default. To sort a 2-D numpy array column-wise, pass `axis=0`

to the function.

import numpy as np # create a numpy array arr = np.array([[3,1,2],[7,9,8],[6,5,4]]) print("Original Array") print(arr) # sort the array arr_sorted = np.sort(arr, axis=0) print("Sorted Array") print(arr_sorted)

Output:

Original Array [[3 1 2] [7 9 8] [6 5 4]] Sorted Array [[3 1 2] [6 5 4] [7 9 8]]

Here you can see that the 2-D numpy array gets sorted such that the columns are sorted.

For more on the numpy sort function, refer to its official documentation.

With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having numpy version 1.18.5

**Subscribe to our newsletter for more informative guides and tutorials. ****We do not spam and you can opt out any time.**

Tutorials on numpy arrays –

- How to sort a Numpy Array?
- Create Pandas DataFrame from a Numpy Array
- Different ways to Create NumPy Arrays
- Convert Numpy array to a List – With Examples
- Append Values to a Numpy Array
- Find Index of Element in Numpy Array
- Read CSV file as NumPy Array
- Filter a Numpy Array – With Examples
- Python – Randomly select value from a list
- Numpy – Sum of Values in Array
- Numpy – Elementwise sum of two arrays
- Numpy – Elementwise multiplication of two arrays
- Using the numpy linspace() method
- Using numpy vstack() to vertically stack arrays
- Numpy logspace() – Usage and Examples
- Using the numpy arange() method
- Using numpy hstack() to horizontally stack arrays
- Trim zeros from a numpy array in Python
- Get unique values and counts in a numpy array
- Horizontally split numpy array with hsplit()