Python Pandas How to assign groupby operation results back to columns in parent dataframe?

前端 未结 5 1500
太阳男子
太阳男子 2020-12-07 08:49

I have the following data frame in IPython, where each row is a single stock:

In [261]: bdata
Out[261]:

Int64In         


        
5条回答
  •  独厮守ぢ
    2020-12-07 09:21

    In [97]: df = pandas.DataFrame({'month': np.random.randint(0,11, 100), 'A': np.random.randn(100), 'B': np.random.randn(100)})
    
    In [98]: df.join(df.groupby('month')['A'].sum(), on='month', rsuffix='_r')
    Out[98]:
               A         B  month       A_r
    0  -0.040710  0.182269      0 -0.331816
    1  -0.004867  0.642243      1  2.448232
    2  -0.162191  0.442338      4  2.045909
    3  -0.979875  1.367018      5 -2.736399
    4  -1.126198  0.338946      5 -2.736399
    5  -0.992209 -1.343258      1  2.448232
    6  -1.450310  0.021290      0 -0.331816
    7  -0.675345 -1.359915      9  2.722156
    

提交回复
热议问题