Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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: ??)

like image 723
RazDva Avatar asked Jan 20 '26 13:01

RazDva


1 Answers

IIUC use x.name:

print (df.groupby('class').apply(lambda x: x.name))
class
bird        bird
mammal    mammal
dtype: object
like image 167
jezrael Avatar answered Jan 23 '26 19:01

jezrael