Cranjis
Cranjis

Reputation: 1960

python dataframe what apply function per group withouth loop

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

Answers (2)

Quang Hoang
Quang Hoang

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

yatu
yatu

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

Related Questions