Python Practice › NumPy Programs › Program 47
Sort rows by the first column
Write a NumPy program to sort the rows of an array by the first column.
Input
[[6, 5], [10, 9], [7, 8]]
Output
[[ 6 5] [ 7 8] [10 9]]
Approach
argsorton the column gives the row order.
Solution
import numpy as npa = np.array([[6, 5], [10, 9], [7, 8]])print(a[a[:, 0].argsort()])Output
[[ 6 5] [ 7 8] [10 9]]
Line by line
Line 3
a[:, 0] is the first column; its argsort is the order in which to take the rows.
Learn the concept
New to this topic? Read the lesson, then come back.