What is the Rank.Avg (from Excel) function in Python?

Viewed 372

What is the Python (pandas) equivalent of rank.avg in Excel? For example, if I want to rank column E from E5:E30 in Excel, I can use rank.avg(E5, E5:E30).

Thanks!

2 Answers

Sample Date:

df = pd.DataFrame(data={'Animal': ['fox', 'Kangaroo', 'deer',
                                   'spider', 'snake'],
                        'Number_legs': [4, 2, 4, 8, np.nan]})
df

Rank function:

df['default_rank'] = df['Number_legs'].rank()
df['max_rank'] = df['Number_legs'].rank(method='max')
df['NA_bottom'] = df['Number_legs'].rank(na_option='bottom')
df['pct_rank'] = df['Number_legs'].rank(pct=True)
df

Output:

enter image description here

Use the below to rank the column in pandas

df["column_name"].rank()

Check the docstring for additional options

...To add the column to the end of the dataframe you could do

df["rank_column"] = df["column_name_to_rank"].rank()
Related