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

如何将指定DataFrame的Excel数据透视表操作转换为Pandas代码?

Pandas实现Excel透视表效果的代码指导

原始数据

以下是你的CSV对应的DataFrame内容:

item_group item_code  total_qty  total_amount cost_center
0           Drink   IC06-1P          1         3.902  Cafe II
1           Drink    IC09-1          1         2.927  Cafe II
2       BreakFast    FS04-2          1         6.463  Cafe II
3           Drink    IC08-1          1         2.927  Cafe II
4           Drink    DT05-1          1         2.561  Cafe II
..            ...       ...        ...           ...          ...
79  Standard Food    FS01-2         12        83.412  Cafe II
80  Standard Food    FS01-1         13       101.465  Cafe II
81          Drink    IC05-1         14        54.628   Cafe I
82  Standard Food    FS01-2         35       243.285   Cafe I
83  Standard Food    FS01-1         44       343.420   Cafe I

对应Excel透视表的Pandas代码

根据你提供的Excel透视表效果(行维度为cost_center和item_group,列维度为item_code,值为total_qty和total_amount的求和,同时包含行总计),可以用Pandas的pivot_table函数实现,代码如下:

完整代码

import pandas as pd

# 读取CSV数据(替换成你的文件实际路径)
df = pd.read_csv("your_data.csv")

# 生成透视表
pivot_df = pd.pivot_table(
    df,
    index=["cost_center", "item_group"],  # 行标签:成本中心、商品组
    columns="item_code",  # 列标签:商品编码
    values=["total_qty", "total_amount"],  # 需要聚合的数值列
    aggfunc="sum",  # 聚合方式:求和
    margins=True,  # 显示总计行/列
    margins_name="总计",  # 总计项的名称
    fill_value=0  # 空值填充为0,避免NaN显示
)

# 打印结果
print(pivot_df)
# 如需导出到Excel,取消注释下面的代码
# pivot_df.to_excel("pivot_result.xlsx")

参数说明

  • index:对应Excel透视表的行标签,设置为cost_center和item_group,按层级展示数据
  • columns:对应Excel透视表的列标签,设置为item_code
  • values:指定需要聚合计算的数值列,这里选择total_qty和total_amount
  • aggfunc="sum":指定聚合逻辑为求和,和Excel透视表的求和功能一致
  • margins=True:开启总计行/列,匹配Excel的“总计”选项
  • fill_value=0:将无数据的单元格填充为0,优化结果可读性

内容的提问来源于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.24 09:57:05