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

Python不使用pandas按指定列分组求和Change_Point问题求助

问题原因分析
  • 第一个报错unsupported operand type(s) for +: 'int' and 'str':从CSV读取的Change_Point默认是字符串类型,直接做数值运算会触发类型不匹配错误
  • 第二个报错'int' object is not iterable:sum()函数要求传入可迭代对象(比如列表、元组等),把单个int类型的Change_Point直接传给sum()就会触发该错误
  • 原有代码逻辑缺陷:首次创建同Order_ID的条目时没有对Change_Point做类型转换和初始化,后续同Order_ID的条目也没有做累加逻辑,同时最终取的其他字段(比如PointRec_ID、Accumulative_Point)需要取当前分组最后一条记录的数值,才能和预期输出匹配
修正后完整代码
import csv
import json

with open('sample.csv','r', encoding='utf-8') as file:
    rows = csv.reader(file, delimiter='|')
    next(rows, None)  # 跳过表头
    orders = {}
    for row in rows:
        PointRec_ID = row[0]        
        Opeartion = row[1]        
        Member_ID = row[2]                
        Order_ID = row[3]        
        Point_Valid_Date = row[4]        
        Point_Invalid_Date = row[5]        
        # 先把Change_Point转成整数
        Change_Point = int(row[6])
        Accumulative_Point = row[7]       
        
        if Order_ID not in orders:
            # 首次出现该订单时初始化,Change_Point赋值为当前值
            orders[Order_ID] = {
                'PointRec_ID': PointRec_ID,
                'Opeartion': Opeartion,
                'Member_ID': Member_ID,
                'Order_ID': Order_ID,
                'Point_Valid_Date': Point_Valid_Date,
                'Point_Invalid_Date': Point_Invalid_Date,
                'Change_Point': Change_Point,
                'Accumulative_Point': Accumulative_Point,                
            }
        else:
            # 后续同订单的记录,累加Change_Point,同时更新其他字段为最新记录的值
            orders[Order_ID]['Change_Point'] += Change_Point
            orders[Order_ID]['PointRec_ID'] = PointRec_ID
            orders[Order_ID]['Accumulative_Point'] = Accumulative_Point
    
    # 转成列表输出
    y = list(orders.values())
print(json.dumps(y))
输出验证

运行上述代码后,Change_Point的分组求和结果和预期输出完全一致:

  • 订单AD031SA12016866的求和结果:639+0+1 = 640
  • 订单AD031SA12016867的求和结果:89+699+0+1+0+1169 = 1958

如果需要输出CSV格式,只需要把最后生成的列表按|分隔写入文件即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 02:54:04