Home > Enterprise >  Get the name of the category corresponding to the maximum value of a column
Get the name of the category corresponding to the maximum value of a column

Time:04-20

I have a pandas dataframe with football team, football players and the number of minutes played during the season.

Team Player Minutes played
1 a 2
1 b 10
1 c 0
2 a 28
2 b 50
2 e 7
3 c 200
3 p 10

By doing :

df['count_max'] = df.groupby(['Team'])['Minutes played'].transform(max)
df

I get a new column with the maximum number of minutes played for each team

Team Player Minutes played Count_max
1 a 2 10
1 b 10 10
1 c 0 10
2 a 28 50
2 b 50 50
2 e 7 50
3 c 200 200
3 p 10 200

But instead of this information, I would like to display the letter corresponding to the player (b for 1, b for 2 and c for 3). Do you know how can I update my code to do so ?

My expected output is :

Team Player Minutes played Count_max
1 a 2 b
1 b 10 b
1 c 0 b
2 a 28 b
2 b 50 b
2 e 7 b
3 c 200 c
3 p 10 c

CodePudding user response:

You can use idxmax in transform and map the index to Player column.

df['count_max'] = df.groupby('Team')['Minutes played'].transform('idxmax').map(df['Player'])
print(df)

   Team Player  Minutes played count_max
0     1      a               2         b
1     1      b              10         b
2     1      c               0         b
3     2      a              28         b
4     2      b              50         b
5     2      e               7         b
6     3      c             200         c
7     3      p              10         c
  • Related