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

How to Sort a NumPy Array by a Specific Column?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-04 17:54:11594browse

How to Sort a NumPy Array by a Specific Column?

Sorting NumPy Arrays Based on Specific Columns

This query addresses the need to sort a NumPy array according to its designated nth column. To illustrate, let's work with an array 'a':

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

Our goal is to sort the rows of matrix 'a' based on its second column, resulting in:

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

To achieve this, we can harness the ability to slice NumPy arrays based on indices and leverage the argsort function. The code below demonstrates the solution:

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

Breaking down this code:

  1. a[:, 1]: This selects the second column of 'a'.
  2. .argsort(): This generates an array of indices representing the sorted order of the elements in the second column.
  3. a[a[:, 1].argsort()]: This rearranges the rows of 'a' according to the sorted indices, leading to the desired result.

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