Sort rows by the first column
EasyNumPy Programs · 47 of 100
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
argsort on the column gives the row order.
Solution
Python
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 3a[:, 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.
More numpy programs
← All 100 NumPy Programs