How to apply a user defined function column wise on grouped data in pandas. The user defined function returns a series of fixed shape.
def getStats(col):
names = ['mean', 'std']
return pd.Series([np.mean(col), np.std(col)], index = names, name = col.name)
df = pd.DataFrame({'city':['c1','c2','c1','c2'],
'age':[10,20,30,40],
'sal':[1000,2000,3000,4000]})
grp_data = df.groupby('city')
grp_data.apply(getStats)
I have tried above snippet. But I am not getting the result in expected format.
city| level| age | sal
c1 | mean | x | y
c2 | std | x1 | y1
Could you pls help on this.