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

如何为Pandas透视表生成的字典列表添加行总计字段?

为透视后的字典列表添加行合计字段

方法一:在Pandas阶段直接计算(推荐)

利用Pandas的行求和功能,在生成透视表后直接添加total列,再转成字典列表,这种方式比后续遍历字典更高效,尤其适合大数据量场景。

完整代码如下:

from pprint import pprint
import pandas as pd

input = [
    {"item": "i1", "balance": 11, "warehouse": "W1"},
    {"item": "i1", "balance": 12, "warehouse": "W4"},
    {"item": "i1", "balance": 13, "warehouse": "W3"},
    {"item": "i2", "balance": 11, "warehouse": "W2"},
    {"item": "i2", "balance": 10, "warehouse": "W1"},
    {"item": "i3", "balance": 10, "warehouse": "W3"},
]

df = pd.DataFrame(input)
df_pivot = df.pivot_table(
    index=["item"], columns="warehouse", values="balance", fill_value=0
)

# 新增total列,对每行的仓库数值求和
df_pivot['total'] = df_pivot.sum(axis=1)

print(df_pivot)
output = df_pivot.reset_index().to_dict(orient="records")
pprint(output)

关键说明:

  • df_pivot.sum(axis=1):axis=1参数指定按行求和,自动计算当前行所有仓库列(W1、W2等)的数值总和
  • 新增的total列会被包含在后续转换的字典列表中,无需额外遍历处理

方法二:遍历已生成的字典列表处理

如果已经得到了未包含total的字典列表,也可以通过遍历每个字典计算合计值:

# 假设已有原始output列表
output = [
 {'W1': 11, 'W2': 0, 'W3': 13, 'W4': 12, 'item': 'i1'},
 {'W1': 10, 'W2': 11, 'W3': 0, 'W4': 0, 'item': 'i2'},
 {'W1': 0, 'W2': 0, 'W3': 10, 'W4': 0, 'item': 'i3'}
]

# 为每个记录添加total字段
for record in output:
    # 筛选所有以W开头的键对应的数值求和
    total = sum(value for key, value in record.items() if key.startswith('W'))
    record['total'] = total

pprint(output)

关键说明:

  • 用key.startswith('W')筛选仓库列,避免误加item字段的值
  • 直接在原字典中新增total字段,无需创建新列表

内容的提问来源于stack exchange,提问作者tree em

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 15:32:56