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
Release: 2024-11-29 18:49:13
Original
770 people have browsed it

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]])
Copy after login

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

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

Solution:

To achieve the desired sorting, use the following code:

a[a[:, 1].argsort()]
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template