Home >Backend Development >Python Tutorial >How Do I Sort a NumPy Array by a Specific Column?

How Do I Sort a NumPy Array by a Specific Column?

DDD
DDDOriginal
2024-11-29 18:49:13769browse

How Do I Sort a NumPy Array by a Specific Column?

Sorting NumPy Arrays by Column: A Comprehensive Guide

Sorting arrays in NumPy by their specific columns is a crucial aspect of data manipulation. This guide provides a comprehensive explanation of how to perform this operation, addressing the following question:

How do I sort a NumPy array by its nth column?

For example, given:

a = np.array([[9, 2, 3],
           [4, 5, 6],
           [7, 0, 5]])

You want to sort the rows of a by the second column to obtain:

array([[7, 0, 5],
       [9, 2, 3],
       [4, 5, 6]])

Solution:

To achieve the desired sorting, use the following code:

a[a[:, 1].argsort()]

This code sorts the array a by the values in its second column (column index 1). The key lies in the .argsort() function. It generates the indices of the sorted values in the second column, which are then used to rearrange the rows of the array accordingly.

The resulting array will be sorted by the second column, with the rows arranged in ascending order based on the values in that column.

The above is the detailed content of How Do I Sort a NumPy Array by a Specific Column?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn