我正在尝试使用 python 数据框中的两列来计算加权和。
数据框结构:
unique_id weight value
1 0.061042375 20.16094523
1 0.3064548 19.50932003
1 0.008310739 18.76469039
1 0.624192086 21.25
2 0.061042375 20.23776924
2 0.3064548 19.63366165
2 0.008310739 18.76299395
2 0.624192086 21.25
.......
我想要的输出是:
每个 unique_id 的加权总和 = sum((weight) * (value))
示例:unique_id 1 的加权总和 = ( (0.061042375 * 20.16094523) + (0.3064548 * 19.50932003) + (0.008310739 * 18.76469039) + (0.624192086 * 21.25) )
我查看了这个答案 ( Calculate weighted average using a pandas/dataframe ),但无法找出将其应用于我的特定场景的正确方法。
这就是我根据上述答案所做的:
#Assume temp_weighted_sum_dataframe is the dataframe stated above
grouped_data = temp_weighted_sum_dataframe.groupby('unique_id') #I think this groups data based on unique_id values
weighted_sum_output = (grouped_data.weight * grouped_data.value).transform("sum") #This should allow me to multiple weight and value for every record within each group and sum it up to one value for that group.
# On above line I am getting the error > TypeError: unsupported operand type(s) for *: 'SeriesGroupBy' and 'SeriesGroupBy'
感谢任何帮助,谢谢
请您参考如下方法:
链接问题中接受的答案确实可以解决您的问题。但是,我会用一个 groupby 以不同的方式解决它:
u = (df.assign(s=df['weight']*df['value'])
.groupby('unique_id')
[['s', 'weight']]
.sum()
)
u['s']/u['weight']
输出:
unique_id
1 20.629427
2 20.672208
dtype: float64
