Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a name header for a lambda function within groupby in python [duplicate]

Tags:

python

pandas

I am using the following code to groupby and count/sum etc.

groups = df[df['isTrade'] == 1].groupby('dateTime')                         
grouped = (groups.agg({'tradeBid': [np.sum,lambda x: (x > 0).sum()],})) 

The output is giving me:

tradeBid    tradeBid
sum <lambda>

79  46
7   6
4   4
20  6

How can I change the output's header ( so my end user will know what is this data?

like image 711
Giladbi Avatar asked Sep 08 '25 14:09

Giladbi


1 Answers

You can provide names like this:

groups.agg({
  'tradeBid': [
    ('sum', np.sum),
    ('other', lambda x: (x > 0).sum())
  ]
})

It used to be you could use a dict instead of a list of 2-tuples, but that is now deprecated (probably because the ordering of the columns is then arbitrary).

like image 78
John Zwinck Avatar answered Sep 10 '25 07:09

John Zwinck