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

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

DDD
Release: 2024-12-25 08:56:09
Original
711 people have browsed it

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

Sorting a NumPy Array by Column

Sorting a NumPy array by its specific column can often be a necessary operation for data manipulation. For instance, consider the array:

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

Suppose we want to reorder the rows of a based on the values in the second column. To achieve this, we can utilize the argsort() function in NumPy.

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

The above expression applies argsort() to the second column of a, producing an array of indices that correspond to the sorted values. Specifically, it returns:

array([1, 0, 2])
Copy after login

These indices represent the order in which the rows of a should be reordered to sort by the second column in ascending order. Combining this with array indexing, we can obtain the sorted array:

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

This expression returns:

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

As desired, the rows of a have been sorted according to the second column.

The above is the detailed content of How Can 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