How to Sort Array by Column in NumPy

Muhammad Maisam Abbas Feb 02, 2024
  1. NumPy Sort Array by Column With the numpy.sort() Function
  2. NumPy Sort Array by Column With the numpy.argsort() Function
How to Sort Array by Column in NumPy

This tutorial will introduce methods to sort an array by column in NumPy.

NumPy Sort Array by Column With the numpy.sort() Function

Suppose we have a 2D NumPy array, and we want to sort the rows according to the order of elements inside a specific column. We can do this with the numpy.sort() function. The numpy.sort() function sorts the NumPy array. We can specify the column index and the axis in the order and axis parameters of the numpy.sort() function. We need to convert our array into a structured array with fields to use the numpy.sort() function. We can use the numpy.view() function to do that. See the following code example.

import numpy as np

array = np.array([[1, 1, 2], [0, 0, 1], [1, 1, 3]])
print("Array before sorting\n", array)

array.view("i8,i8,i8").sort(order=["f1"], axis=0)
print("Array after sorting\n", array)

Output:

Array before sorting
 [[1 1 2]
 [0 0 1]
 [1 1 3]]
Array after sorting
 [[0 0 1]
 [1 1 2]
 [1 1 3]]

We first created the 2D NumPy array array with the np.array() function. Then we converted the array to a structured array with the array.view() function. After that, we sorted the array by second column with sort(order=['f1'], axis=0) function. Here, f1 refers to the second column.

NumPy Sort Array by Column With the numpy.argsort() Function

Another more simple way of doing the exact same thing as the previous approach is to use the numpy.argsort() function. The numpy.argsort() function is also used to sort the elements of an array. It is very similar to the previous approach, but we do not need to use the numpy.view() function for this approach to work. The numpy.argsort() function returns the indices that would be used to sort an array. See the following code example.

import numpy as np

array = np.array([[1, 1, 2], [0, 0, 1], [1, 1, 3]])
print("Array before sorting\n", array)

array[array[:, 1].argsort()]
print("Array after sorting\n", array)

Output:

Array before sorting
 [[1 1 2]
 [0 0 1]
 [1 1 3]]
Array after sorting
 [[0 0 1]
 [1 1 2]
 [1 1 3]]

We first created a 2D NumPy array array with the np.array() function. We then used an array slice to specify only the second column of the array and sorted it with the np.argsort() function. We used the indices returned by the np.argsort() function to sort the array.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn