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]])
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()
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])
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()]
This expression returns:
array([[7, 0, 5], [9, 2, 3], [4, 5, 6]])
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!