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

如何基于多列DataFrame按产品分类计算聚合营收结果

pandas按产品分类聚合统计营收实现方案

你可以直接通过pandas内置的链式方法单行完成全部计算,也可以拆分为多步写法方便调试,两种方式逻辑完全一致。

核心计算规则

单条记录营收 = (UnitPrice - Product Standard Cost) × Sales Amount,最终按Category维度对所有单条记录营收求和,得到各分类总营收。

涉及的原始DataFrame字段如下:

  • UnitPrice:产品单价
  • Category:产品分类标识
  • Product Standard Cost:产品标准成本
  • Sales Amount:销售核算金额

单行实现代码

# 注意列名带空格时必须用方括号形式取列,不能用df.列名的点访问写法
category_revenue_df = df.assign(record_rev=(df['UnitPrice'] - df['Product Standard Cost']) * df['Sales Amount']).groupby('Category', as_index=False)['record_rev'].sum().rename(columns={'record_rev':'total_revenue'})

代码逻辑拆解:

  • 用assign方法临时生成单条记录营收的中间列,不会修改原始DataFrame
  • 用groupby按分类字段聚合
  • 对营收列求和后重命名为更易读的总营收列名

分步实现(可读性更高,推荐日常使用)

如果觉得单行代码太长不方便排查问题,可以拆成3步写:

# 1. 计算每条记录的营收
df['record_revenue'] = (df['UnitPrice'] - df['Product Standard Cost']) * df['Sales Amount']
# 2. 按分类聚合求和
category_revenue_df = df.groupby('Category', as_index=False)['record_revenue'].sum()
# 3. 重命名输出列
category_revenue_df = category_revenue_df.rename(columns={'record_revenue': 'total_category_revenue'})

注意:如果你的Product Standard Cost实际列名是无空格的驼峰命名ProductStandardCost,只需要把代码里对应列名替换成实际字段名即可,计算逻辑不需要调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 17:42:25