简体   繁体   中英

pandas groupby apply on multiple columns

I am trying to apply the same function to multiple columns of a groupby object, such as:

In [51]: df
Out[51]: 
           a         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 I 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 will give me ValueError: could not convert string to float: grp1 . What is the correct way to apply the function to multiple columns at once?

I think you are looking for transform - it applies a function to each group.

>>> df.groupby('group').transform(pd.rolling_mean, 2, min_periods=2)
           a         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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM