Compute numerical rankings for values along an axis using the Pandas rank() method. Handle tied values using tie-breaking strategies (average, min, max, first, dense), rank in ascending or descending order, and compute percentile ranks.
rank() method computes numerical ranks (1 through N) for elements in a Series or DataFrame column. By default, smaller values receive lower rank positions (ascending order), and tied values receive their average rank position.import pandas as pd
df = pd.DataFrame({
"STUDENT": ["Ravi", "Raju", "Alex", "John", "Sara"],
"SCORE": [80, 90, 80, 95, 70]
})
print(df)
assert df.shape == (5, 2)
Expected output
STUDENT SCORE
0 Ravi 80
1 Raju 90
2 Alex 80
3 John 95
4 Sara 70
ascending=False to rank from highest score (Rank 1) to lowest score.df["RANK_DESC"] = df["SCORE"].rank(ascending=False)
print(df)
assert df.loc[3, "RANK_DESC"] == 1.0
Expected output
STUDENT SCORE RANK_DESC
0 Ravi 80 3.5
1 Raju 90 2.0
2 Alex 80 3.5
3 John 95 1.0
4 Sara 70 5.0
"average": Default. Assigns average rank to tied items (e.g., 3.5)."min": Assigns lowest rank of the group to all tied items."max": Assigns highest rank of the group to all tied items."first": Ranks tied items based on order of appearance in the data."dense": Like "min", but rank always increases by 1 for the next group (no gaps).df["MIN_RANK"] = df["SCORE"].rank(ascending=False, method="min")
df["DENSE_RANK"] = df["SCORE"].rank(ascending=False, method="dense")
print(df[["STUDENT", "SCORE", "MIN_RANK", "DENSE_RANK"]])
assert df.loc[0, "MIN_RANK"] == 3.0 and df.loc[4, "DENSE_RANK"] == 4.0
Expected output
STUDENT SCORE MIN_RANK DENSE_RANK
0 Ravi 80 3.0 3.0
1 Raju 90 2.0 2.0
2 Alex 80 3.0 3.0
3 John 95 1.0 1.0
4 Sara 70 5.0 4.0
pct=True to rescale values between 0.0 and 1.0, returning the relative percentile rank.df["PCT_RANK"] = df["SCORE"].rank(pct=True)
print(df[["STUDENT", "SCORE", "PCT_RANK"]])
assert df.loc[3, "PCT_RANK"] == 1.0
Expected output
STUDENT SCORE PCT_RANK
0 Ravi 80 0.5
1 Raju 90 0.8
2 Alex 80 0.5
3 John 95 1.0
4 Sara 70 0.2
sales = pd.Series([500, 700, 500, 900], name="SALES"), compute a descending rank using method="min". Verify that the highest sales figure receives Rank 1.0.rank().sales = pd.Series([500, 700, 500, 900], name="SALES")
answer = sales.rank(ascending=False, method="min")
print(answer)
assert answer[3] == 1.0
Expected output
0 3.0
1 2.0
2 3.0
3 1.0
Name: SALES, dtype: float64
Practice rank() examples interactively directly in your browser:
Reference: Pandas rank() documentation.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.