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]])
You want to sort the rows of a by the second column to obtain:
array([[7, 0, 5], [9, 2, 3], [4, 5, 6]])
Solution:
To achieve the desired sorting, use the following code:
a[a[:, 1].argsort()]
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!