Skip to main content

Introduction to Python NumPy Sorting Arrays

Python NumPy Sorting Arrays

In NumPy, you can sort arrays in various ways using different functions.

Here are some common functions for sorting arrays:

Using np.sort()

The np.sort() function returns a sorted copy of an array. By default, it sorts the array in ascending order along the last axis.

import numpy as np

arr = np.array([3, 2, 1, 5, 4])

# Sort the array in ascending order
sorted_arr = np.sort(arr)
print(sorted_arr)

Output:

[1 2 3 4 5]

Using np.argsort()

The np.argsort() function returns the indices that would sort an array. It returns an array of indices that would sort the original array in ascending order.

import numpy as np

arr = np.array([3, 2, 1, 5, 4])

# Get the indices that would sort the array
indices = np.argsort(arr)
print(indices)

Output:

[2 1 0 4 3]

Using np.sort(axis=0)

You can use the axis parameter of np.sort() to sort the array along a specific axis.

Output:

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

Using np.sort(axis=None)

If you set axis to None, the np.sort() function will flatten the array and sort the elements in ascending order.

import numpy as np

arr = np.array([[3, 2, 1],
[6, 5, 4]])

# Sort the flattened array
sorted_arr = np.sort(arr, axis=None)
print(sorted_arr)

Output:

[1 2 3 4 5 6]