python - pandas groupby apply on multiple columns -


i trying apply same function multiple columns of groupby object, such as:

in [51]: df out[51]:                     b group 0   0.738628  0.242605  grp1 1   0.411315  0.340703  grp1 2   0.328785  0.780767  grp1 3   0.059992  0.853132  grp1 4   0.041380  0.368674  grp1 5   0.181592  0.632006  grp1 6   0.427660  0.292086  grp1 7   0.582361  0.239835  grp1 8   0.158401  0.328503  grp2 9   0.430513  0.540628  grp2 10  0.436652  0.085609  grp2 11  0.164037  0.381844  grp2 12  0.560781  0.098178  grp2  in [52]: df.groupby('group')['a'].apply(pd.rolling_mean, 2, min_periods = 2) out[52]:  0          nan 1     0.574971 2     0.370050 3     0.194389 4     0.050686 5     0.111486 6     0.304626 7     0.505011 8          nan 9     0.294457 10    0.433582 11    0.300345 12    0.362409 dtype: float64  in [53]:  

however, if try df.groupby('group')['a', 'b'].apply(pd.rolling_mean, 2, min_periods = 2) or df.groupby('group')[['a', 'b']].apply(pd.rolling_mean, 2, min_periods = 2), both give me valueerror: not convert string float: grp1. correct way apply function multiple columns @ once?

i think looking transform - applies function each group.

>>> df.groupby('group').transform(pd.rolling_mean, 2, min_periods=2)                    b 0        nan       nan 1   0.574971  0.291654 2   0.370050  0.560735 3   0.194388  0.816950 4   0.050686  0.610903 5   0.111486  0.500340 6   0.304626  0.462046 7   0.505010  0.265961 8        nan       nan 9   0.294457  0.434566 10  0.433582  0.313119 11  0.300344  0.233727 12  0.362409  0.240011 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -