如何用Python Pandas计算各商品加权均价并生成新DataFrame
问题:计算商品加权平均价格并生成新DataFrame
我有一个包含多种商品的DataFrame,每种商品在一年内有多次采购记录,对应不同的Price(价格)和Weight(数量)。需要计算每种商品的加权平均价格,并将商品与其加权均价对应映射到新的DataFrame中。
数据示例
Year Article Price Weight 18 2013 Cheese 18.0 26.0 19 2013 Apple 5.0 7.0 20 2013 Bun 2.0 2.0 21 2013 Coatl 4.0 5.0 22 2013 Cheese 20.0 21.0 23 2013 Peach 12.0 8.0 24 2013 Apple 4.6 3.0
尝试的错误代码
import pandas as pd df = newonly2013 def weightedAverage(df,Weight,Price): return sum(df['Weight']*df['Price'])/sum(df['Weight']) wa=weightedAverage(df,'Weight','Price') ar = df.groupby('Article', as_index=False).apply(weightedAverage) print(ar)
错误原因与解决方法
错误分析
- 调用
groupby.apply时,未给自定义函数传递Weight和Price参数,导致函数因缺少参数报错。 - 使用Python内置
sum()方法不如pandas的.sum()高效,且不符合pandas最佳实践。
修正后的代码(自定义函数版)
import pandas as pd df = newonly2013 def weightedAverage(group, weight_col, price_col): # 用pandas的sum方法计算加权和与总权重 return (group[weight_col] * group[price_col]).sum() / group[weight_col].sum() # 分组时传递函数所需参数 ar = df.groupby('Article', as_index=False).apply( weightedAverage, weight_col='Weight', price_col='Price' ) # 重命名结果列,明确含义 ar.columns = ['Article', 'Weighted_Average_Price'] print(ar)
更简洁的实现(无需自定义函数)
直接用groupby结合lambda表达式,代码更紧凑:
import pandas as pd df = newonly2013 # 分组计算加权均价,用reset_index将索引转为列 ar = df.groupby('Article').apply( lambda x: (x['Price'] * x['Weight']).sum() / x['Weight'].sum() ).reset_index(name='Weighted_Average_Price') print(ar)
或者用agg方法,可读性更强:
ar = df.groupby('Article').agg( Weighted_Average_Price=lambda x: (x['Price'] * x['Weight']).sum() / x['Weight'].sum() ).reset_index()
结果示例
运行后会得到如下格式的新DataFrame:
Article Weighted_Average_Price 0 Apple 4.88 1 Bun 2.00 2 Coatl 4.00 3 Cheese 18.89 4 Peach 12.00
内容的提问来源于stack exchange,提问作者D S G
相关产品推荐
相关产品推荐

