How to Sort a NumPy Array by Column (With Examples)

Sorting a NumPy array by column can be done using the ndarray.sort() method. This method takes an optional argument which is the axis along which to sort. Additionally, the kind of sorting algorithm used can be specified using the kind parameter. Examples of sorting by column are given in the code snippet below, which sorts an array by its second column in ascending order and its third column in descending order.


You can use the following methods to sort the rows of a NumPy array by column values:

Method 1: Sort by Column Values Ascending

x_sorted_asc = x[x[:, 1].argsort()]

Method 2: Sort by Column Values Descending

x_sorted_desc = x[x[:, 1].argsort()[::-1]]

The following examples show how to use each method in practice.

Example 1: Sort Numpy Array by Column Values Ascending

Suppose we have the following NumPy array:

import numpy as np

#create array
x = np.array([14, 12, 8, 10, 5, 7, 11, 9, 2]).reshape(3,3)

#view array
print(x)

[[14 12  8]
 [10  5  7]
 [11  9  2]]

We can use the following code to sort the rows of the NumPy array in ascending order based on the values in the second column:

#define new matrix with rows sorted in ascending order by values in second column
x_sorted_asc = x[x[:, 1].argsort()]

#view sorted matrix
print(x_sorted_asc)

[[10  5  7]
 [11  9  2]
 [14 12  8]]

Notice that the rows are now sorted in ascending order (smallest to largest) based on the values in the second column.

Example 2: Sort Numpy Array by Column Values Descending

Suppose we have the following NumPy array:

import numpy as np

#create array
x = np.array([14, 12, 8, 10, 5, 7, 11, 9, 2]).reshape(3,3)

#view array
print(x)

[[14 12  8]
 [10  5  7]
 [11  9  2]]

We can use the following code to sort the rows of the NumPy array in descending order based on the values in the second column:

#define new matrix with rows sorted in descending order by values in second column
x_sorted_desc = x[x[:, 1].argsort()[::-1]]

#view sorted matrix
print(x_sorted_desc)

[[14 12  8]
 [11  9  2]
 [10  5  7]]

The following tutorials explain how to perform other common operations in Python:

x