如何用Pandas按条件计算库存加权平均成本(WAC)并汇总
按规则计算库存加权平均成本(WAC)并汇总
核心思路
由于WAC的计算依赖同产品上一笔交易的结果,属于状态依赖型计算,无法直接用cumsum这类向量化函数实现,需要按Product ID分组后逐行迭代计算。我们可以用groupby().apply()结合自定义函数来处理每组内的逻辑。
步骤1:构造示例数据(可替换为你的真实数据)
import pandas as pd data = { 'Product ID': ['A', 'A', 'A', 'B', 'B'], 'Initial stock': [10, 15, 20, 5, 8], 'Initial unit cost': [100, 100, 105, 200, 200], 'Reference': ['Purch.', 'Sale', 'Purch.', 'Sale', 'Purch.'], 'Quantity': [5, -3, 4, -2, 3], 'Unit cost': [110, None, 120, None, 210], 'Current stock': [15, 12, 16, 3, 6] } df = pd.DataFrame(data)
步骤2:定义WAC计算函数
针对每个产品的分组数据,严格按照你给出的规则逐行计算WAC:
def calculate_wac(group): # 重置分组内索引,确保从0开始迭代 group = group.reset_index(drop=True) wac_values = [] for idx in range(len(group)): if idx == 0: # 处理首行逻辑 if group.loc[idx, 'Reference'] == 'Purch.': wac = (group.loc[idx, 'Initial stock'] * group.loc[idx, 'Initial unit cost'] + group.loc[idx, 'Quantity'] * group.loc[idx, 'Unit cost']) / group.loc[idx, 'Current stock'] else: wac = group.loc[idx, 'Initial unit cost'] else: # 处理后续行逻辑 if group.loc[idx, 'Reference'] == 'Purch.': wac = (group.loc[idx-1, 'Current stock'] * wac_values[idx-1] + group.loc[idx, 'Quantity'] * group.loc[idx, 'Unit cost']) / group.loc[idx, 'Current stock'] else: wac = wac_values[idx-1] wac_values.append(wac) group['WAC'] = wac_values return group
步骤3:分组计算WAC
将函数应用到每个产品分组:
df_with_wac = df.groupby('Product ID').apply(calculate_wac).reset_index(drop=True)
步骤4:按产品汇总最终结果
提取每个产品最后一笔交易的Current stock和WAC作为最终汇总:
summary_df = df_with_wac.groupby('Product ID').agg( Final_Current_Stock=('Current stock', 'last'), Final_WAC=('WAC', 'last') ).reset_index()
关键注意事项
- 交易顺序:如果你的原始数据没有按交易发生顺序排列,一定要在
calculate_wac函数中先对分组数据排序(比如添加group = group.sort_values('交易时间列')),否则计算结果会完全错误。 - 空值处理:销售记录的
Unit cost可以为空,因为代码逻辑中不会用到这部分值。 - 精度控制:如果需要保留特定小数位数,可以在计算后用
round()处理,比如wac = round(wac, 2)。
内容的提问来源于stack exchange,提问作者cmoreno98
相关产品推荐
相关产品推荐

