Reputation: 5355
Say I have the following dataframe df_grouped
:
Sale
custid | product |
-------+-----------+------
1 | iPhone | 3000
| android | 2000
2 | iPhone | 1500
| android | 2500
and I want a ranking within each group (customerid
) ending with
Sale
custid | product |
-------+-----------+------
1 | iPhone | 1
| android | 2
2 | iPhone | 2
| android | 1
If I just do df_grouped.rank()
I get a global ranking
Sale
custid | product |
-------+-----------+------
1 | iPhone | 1
| android | 3
2 | iPhone | 4
| android | 2
but I want the ranking within each group. I can loop over each custid
and apply rank
to each of those groups, but isn't there a faster/cleaner way?
Upvotes: 1
Views: 49
Reputation: 862511
Use GroupBy.rank
:
df['Rank'] = df.groupby(level='custid')['Sale'].rank()
Upvotes: 1