Home > Mobile >  Can I get the value of the grouped column in groupby apply?
Can I get the value of the grouped column in groupby apply?

Time:11-26

Can I get the value of grouped column in apply in pandas groupby? For example,

df = pd.DataFrame([('bird', 389.0),
                   ('bird', 24.0),
                   ('mammal', 80.5),
                   ('mammal', np.nan)],
                  index=['falcon', 'parrot', 'lion', 'monkey'],
                  columns=('class', 'max_speed'))

I used group by for column class and want to use the value of class in x df.groupby('class').apply(lambda x: ??)

CodePudding user response:

IIUC use x.name:

print (df.groupby('class').apply(lambda x: x.name))
class
bird        bird
mammal    mammal
dtype: object
  • Related