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

如何拆分并合并AF与CA的表格数据?代码问题排查

问题排查与正确实现方法

现有代码的问题

  • 参数设计不合理:仅接收单个DataFrame参数,但实际需要处理Table1、Table2两个数据集
  • 核心逻辑错误:
    • 循环执行一次就通过return()终止,CA类别完全没被处理
    • df.append(item)是把字符串"AF"追加到DataFrame,完全偏离了按类别汇总数值的需求
    • 缺少合并两个表格、按Col1分组求和的关键逻辑

正确实现代码

假设原始数据以pandas DataFrame形式存储,以下是实现分组汇总的代码:

import pandas as pd

# 模拟原始数据
table1 = pd.DataFrame({
    "Col1": ["AF", "CA"],
    "Col 2": [98, 10],
    "Col3": [45, 68]
})

table2 = pd.DataFrame({
    "Col1": ["AF", "CA"],
    "Col 2": [2, 100],
    "Col3": [45, 6]
})

# 合并两个表格
combined_df = pd.concat([table1, table2])

# 按Col1分组,对数值列求和
summary = combined_df.groupby("Col1").sum().reset_index()

# 输出结果
for _, row in summary.iterrows():
    print(f"Table for {row['Col1']}: ")
    print(pd.DataFrame([row.values], columns=summary.columns))
    print()

执行结果

Table for AF: 
  Col1  Col 2  Col3
0   AF    100    90

Table for CA: 
  Col1  Col 2  Col3
0   CA    110    74

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:03:27