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

如何将现有DataFrame转换为按Party分组带Cash汇总行的格式?

Pandas实现Party汇总行前置的DataFrame转换

实现思路

  • 提取每个Party的Cash汇总行:用已计算好的agg_x和agg_y作为汇总行的x、y值,将Product字段设为"Cash",同步保留对应Party的Currency和Parent信息
  • 整理原始产品记录:保留需求指定的字段,移除agg_x、agg_y等冗余字段
  • 合并并排序:通过添加排序辅助列,确保每个Party的Cash汇总行排在该Party所有产品记录的最前面

代码实现

import pandas as pd

# 假设原始DataFrame名为df
# 1. 生成每个Party的Cash汇总行
summary_rows = df.groupby('Party').agg(
    Product=('Product', lambda _: 'Cash'),
    x=('agg_x', 'first'),  # 同Party的agg_x值一致,取首个即可
    y=('agg_y', 'first'),
    Currency=('Currency', 'first'),  # 若同Party存在多Currency,需按需调整逻辑
    Parent=('Parent', 'first')       # 若同Party存在多Parent,需按需调整逻辑
).reset_index()

# 2. 处理原始产品记录,保留目标字段
product_rows = df[['Product', 'Party', 'x', 'y', 'Currency', 'Parent']].copy()

# 3. 添加排序辅助列,确保Cash行优先
summary_rows['sort_key'] = 0
product_rows['sort_key'] = 1

# 合并数据并排序
result_df = pd.concat([summary_rows, product_rows], ignore_index=True)
result_df = result_df.sort_values(by=['Party', 'sort_key'], ascending=[True, True])

# 清理辅助列并重置索引
result_df = result_df.drop(columns='sort_key').reset_index(drop=True)

关键说明

  • 若同Party的Currency或Parent存在多个不同值,可修改agg方法中的逻辑(例如用unique()去重,或根据业务规则选取特定值)
  • 排序辅助列sort_key是实现汇总行前置的核心,通过0和1的排序优先级确保Cash行始终在同Party记录的最上方

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 03:36:20