sort a numpy array

How to sort a Numpy Array?

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

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).

Let’s look at some examples and use-cases of sorting a 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:

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

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.

The numpy ndarray sort() and the numpy sort() function take additional arguments – axis, kind, and order.

  • axis: The axis along which to sort the array. Defaults to -1, that is, sort along the last axis.
  • kind: The sorting algorithm to use. The available options are 'quicksort', 'mergesort', 'heapsort', and 'stable'. The default is 'quicksort'.
  • order: Used in numpy arrays with defined fields. It determines which fields to compare first.

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.

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].

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.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top