![]() |
VOOZH | about |
Ranking rows in a Pandas DataFrame assigns a numerical rank to each row based on the values in a column. Higher or lower values can be ranked first depending on the requirement.
For example, given a small dataset of students’ scores, we can rank them to see who scored highest and lowest.
Student Marks Rank 0 Emily 85 2.0 1 Ava 92 1.0 2 Jack 78 3.0
Explanation:
DataFrame.rank(axis=0, method='average', ascending=True)
Parameters:
Return Value: Returns a Series or DataFrame containing ranks.
Example 1: In this example, we rank movies from lowest to highest rating using the rank() method.
Output
Movie Year Rating Rank_Asc
1 Bird Box 2018 6.8 1.0
4 Titanic 1997 7.8 2.0
3 Inception 2010 8.7 3.0
2 Fight Club 1999 8.8 4.0
0 The Godfather 1972 9.2 5.0
Explanation:
Example 2: This code ranks movies from highest to lowest rating to find the top-rated movie.
Output
Movie Year Rating Rank_Desc
0 The Godfather 1972 9.2 1.0
2 Fight Club 1999 8.8 2.0
3 Inception 2010 8.7 3.0
4 Titanic 1997 7.8 4.0
1 Bird Box 2018 6.8 5.0
Explanation:
Example 3: Here we rank movies using the 'min' method, which gives tied ratings the minimum possible rank.
Output
Movie Year Rating Rank_Min
0 The Godfather 1972 9.2 1.0
2 Fight Club 1999 8.8 2.0
5 Movie X 2020 8.8 2.0
3 Inception 2010 8.7 4.0
4 Titanic 1997 7.8 5.0
1 Bird Box 2018 6.8 6.0
Explanation: