Reputation: 1960
I have a dataframe
df =
type value
A 5
A 7
B 2
B 6
A 1
I was to apply function per the groups of the column type
, so the rank will apply per type and the new df will be
df =
type value rank
A 5 1
A 7 0
B 2 1
B 6 0
A 1 2
Upvotes: 4
Views: 52
Reputation: 150735
This can be done with a sort_values
followed by groupby().cumcount()
:
df['rank'] = df.sort_values('value', ascending=False).groupby('type').cumcount()
Output:
type value rank
0 A 5 1
1 A 7 0
2 B 2 1
3 B 6 0
4 A 1 2
Upvotes: 1
Reputation: 88226
You can use groupby.rank
, setting ascending=False
:
df['rank'] = df.groupby('type').value.rank(ascending=False).sub(1).astype(int)
print(df)
type value rank
0 A 5 1
1 A 7 0
2 B 2 1
3 B 6 0
4 A 1 2
Upvotes: 0