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