Pandas: Creating aggregated column in DataFrame

前端 未结 4 656
栀梦
栀梦 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:11

    This is not so direct but I found it very intuitive (the use of map to create new columns from another column) and can be applied to many other cases:

    gb = df.groupby('A').sum()['values']
    
    def getvalue(x):
        return gb[x]
    
    df['sum'] = df['A'].map(getvalue)
    df
    

提交回复
热议问题