Reputation: 1147
I am trying to rank a column (col 1)
in pandas. If there is a tie, I want to look at another column (col 2)
just for those records and do a tie breaker. IF they are same even in that column, I want to just assign the ranks randomly but each row must have a unique rank.
Example:
col1 | col 2 | Rank
20 | 3 | 3
22 | 2 | 2
22 | 2.5 | 1
3 | 1 | 4
3 | 1 | 5
Upvotes: 2
Views: 1576
Reputation: 1492
df['Rank'] = df.sort_values(by=['col1', 'col2'], ascending=False) \
.reset_index() \
.sort_values('index') \
.index + 1
This code goes through these steps:
level_0
. If you have both index
and level_0
, the code will throw an exception.Upvotes: 6