You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用pandas对Excel数据指定人员行求和并插入汇总行

pandas 实现指定人员数据求和并插入顶部总计行

直接按以下逻辑实现即可,兼容Excel读写场景:

import pandas as pd

# 读取原始Excel数据,替换为你的实际文件路径
# df = pd.read_excel("你的原始数据.xlsx")

# 以下为示例数据,和你给出的原始表结构一致
df = pd.DataFrame({
    "name": ["john", "edwin", "maria"],
    "salary": [2000, 3000, 1000],
    "incentive": [400, 600, 200]
})

# 筛选指定姓名的行,对目标字段求和
target_person = ["edwin", "maria"]
sum_result = df[df["name"].isin(target_person)][["salary", "incentive"]].sum()

# 构造总计行
total_line = pd.DataFrame({
    "name": ["Total"],
    "salary": [sum_result["salary"]],
    "incentive": [sum_result["incentive"]]
})

# 拼接总计行到原表顶部,自动重置索引
final_df = pd.concat([total_line, df], ignore_index=True)

# 导出结果到Excel,不需要可注释
# final_df.to_excel("处理完成的结果.xlsx", index=False)

运行后得到的表结构和你要求的完全一致,注:按你描述的「仅统计edwin、maria」规则计算,总计行salary应为4000、incentive应为800,如果你给出的预期示例里的5000、1000是需要统计全员或者其他人员组合,直接调整筛选条件即可。

几个实现细节说明:

  • 用isin()做批量值匹配,比写多个或条件更简洁易维护
  • 拼接时传入ignore_index=True会自动生成连续的行索引,不需要手动调整索引值
  • 如果你的表有更多数值字段需要求和,直接在sum的字段列表里追加列名即可

内容的提问来源于stack exchange,提问作者Karishma Upadhyay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 17:18:24