Pandas: Creating aggregated column in DataFrame

前端 未结 4 650
栀梦
栀梦 2020-12-05 04:54

With the DataFrame below as an example,

In [83]:
df = pd.DataFrame({\'A\':[1,1,2,2],\'B\':[1,2,1,2],\'values\':np.arange(10,30,5)})
df
Out[83]:
   A  B  val         


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-05 05:26

    In [15]: def sum_col(df, col, new_col):
       ....:     df[new_col] = df[col].sum()
       ....:     return df
    
    In [16]: df.groupby("A").apply(sum_col, 'values', 'sum_values_A')
    Out[16]: 
       A  B  values  sum_values_A
    0  1  1      10            25
    1  1  2      15            25
    2  2  1      20            45
    3  2  2      25            45
    

提交回复
热议问题