pandas group by, aggregate using multiple agg functions on input columns

Viewed 5888

I am looking to do some aggregation on a pandas groupby dataframe, where I need to apply several different custom functions on multiple columns. This operation is very easy and customary in R (using data.table or dplyr), but I am surprised I'm finding it so difficult in pandas:

import pandas as pd
data = pd.DataFrame({'A':[1,2,3,4,5,6],'B':[2,4,6,8,10,12],'C':[1,1,1,2,2,2]})

#These work
data.groupby('C').apply(lambda x: x.A.mean() - x.B.mean())
data.groupby('C').agg(['mean','std'])

#but this doesn't
data.groupby('C').agg([lambda x: x.A.mean() - x.B.mean(),
                       lambda x: len(x.A)])

I want to calculate a statistic but also the sample size in each group, which seems like it should be a one or two line solution, but I also sometimes need to apply multiple functions on multiple columns of the grouped data frame.

2 Answers
Related