Pandas中跨多个groupby结果执行数学计算:按ID分摊项目成本
Pandas 全量ID成本分摊批量实现方案
核心实现代码
import pandas as pd # 方案1:基于索引直接匹配,无需重置索引,效率更高 # 计算每个ID的总工时,transform返回结果与原Hours表索引完全对齐 id_total_hours = Hours.groupby(level="ID")["Hours"].transform("sum") # 匹配每行ID对应的总成本 id_cost = Hours.index.get_level_values("ID").map(Costs["Cost"]) # 按公式计算分摊成本,保留2位小数 Hours["Allocated Costs"] = (Hours["Hours"] / id_total_hours * id_cost).round(2) # 整理输出格式 result = Hours.drop(columns=["Hours"])
备选实现(更易读的merge方案)
# 先关联两表数据 df = Hours.reset_index().merge(Costs.reset_index(), on="ID", how="left") # 按ID分组计算总工时 df["id_total_hours"] = df.groupby("ID")["Hours"].transform("sum") # 计算分摊成本 df["Allocated Costs"] = (df["Hours"] / df["id_total_hours"] * df["Cost"]).round(2) # 整理为要求的索引格式 result = df[["ID", "Project", "Allocated Costs"]].set_index(["ID", "Project"])
逻辑说明
- 两种方案均为向量化批量计算,无需逐ID循环筛选,可直接处理全量数据
- 输出的
result完全匹配你要求的格式,数值精度为保留两位小数 - 如果你的索引名称不是
ID/Project,替换成对应索引名即可正常运行
内容的提问来源于stack exchange,提问作者user14380579
相关产品推荐
相关产品推荐

