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


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

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

Additional Resources

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

How to Find Index of Value in NumPy Array
How to Get Specific Column from NumPy Array
How to Add a Column to a NumPy Array

Leave a Reply

Your email address will not be published.