使用熊猫/数据框基于2列计算加权平均值

时间:2019-04-08 17:04:33

标签: python pandas dataframe

我有以下数据框df。我想计算按日期和部门级别分组的加权平均值

 date     Equity    value    Sector   Weight
2000-01-31  TLRA    20      RG Index     0.20
2000-02-28  TLRA    30      RG Index     0.20
2000-03-31  TLRA    40      RG Index     0.20
2000-01-31   RA     50      RG Index     0.30
2000-02-28   RA     60      RG Index     0.30
2000-03-31   RA     70      RG Index     0.30
2000-01-31  AAPL    80      SA Index     0.50
2000-02-28  AAPL    90      SA Index     0.50
2000-03-31  AAPL    100     SA Index     0.50
2000-01-31  SPL     110     SA Index     0.60
2000-02-28  SPL     120     SA Index     0.60
2000-03-31  SPL     130     SA Index     0.60

Equity下可以有许多Sector。我想要基于“权重”列的部门级别加权平均。

预期输出:

date        RG Index       SA Index
2000-01-31  19               106  
2000-02-28  24               117
2000-03-31  29               138 

我尝试了下面的代码,但没有得到预期的输出。请帮助

g = df.groupby('Sector')
df['wa'] = df.value / g.value.transform("sum") * df.Weight
df.pivot(index='Sector', values='wa')

1 个答案:

答案 0 :(得分:3)

更像是pivot问题的第assign个新列,是valueweight的乘积

df.assign(V=df.value*df.Weight).pivot_table(index='date',columns='Sector',values='V',aggfunc='sum')
Out[328]: 
Sector      RGIndex  SAIndex
date                        
2000-01-31     19.0    106.0
2000-02-28     24.0    117.0
2000-03-31     29.0    128.0