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

How to Sort a NumPy Array's Rows by a Specific Column?

DDD
DDDOriginal
2024-11-28 21:27:18758browse

How to Sort a NumPy Array's Rows by a Specific Column?

Sorting Arrays in NumPy by Column

Sorting arrays by columns is a common task in data analysis and manipulation. NumPy provides efficient ways to perform this operation.

Question:

Given a NumPy array with multiple columns, how can you sort its rows by a specific column?

Example:

Consider the following array a:

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

We want to sort the rows of a by the second column (column 1, indexed from 0) to obtain:

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

Answer:

To sort a by its second column, use the following code:

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

This expression achieves the desired result because:

  1. a[:, 1] selects the second column of a.
  2. argsort() returns the indices that would sort the column in ascending order.
  3. Indexing a with these indices sorts the rows of a accordingly.

Therefore, this approach provides a convenient and efficient way to sort NumPy arrays by any specified column.

The above is the detailed content of How to Sort a NumPy Array's Rows 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