Home >Backend Development >Python Tutorial >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:
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!