Methods for Sorting Data
Once our data is clean, we may want to arrange it.
sort_values(): The sort_values() method sorts the Series according to its values. By default, it sorts the values in ascending order.
For example:
marks = pd.Series([85, 65, 95, 72])
marks.sort_values()
output:
1 65
3 72
0 85
2 95
dtype: int64
We can sort the values in descending order using:
marks.sort_values(ascending=False)
output:
2 95
0 85
3 72
1 65
dtype: int64
sort_index(): The sort_index() method sorts the Series according to its index rather than its values.
For example:
marks = pd.Series([85, 65, 95], index=["C", "A", "B"])
marks.sort_index()
output:
A 65
B 95
C 85
dtype: int64
This becomes useful when we are working with custom indexes.
nlargest(): The nlargest() method returns the largest n values from the Series.
For example:
marks = pd.Series([85, 72, 90, 65, 95])
marks.nlargest(3)
output:
4 95
2 90
0 85
dtype: int64
Here, the 3 highest marks are returned.
This is useful when we want to find top performers.
nsmallest(): The nsmallest() method returns the smallest n values from the Series.
For example:
marks = pd.Series([85, 72, 90, 65, 95])
marks.nsmallest(3)
output:
3 65
1 72
0 85
dtype: int64
Here, the 3 lowest marks are returned.