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

Python字典列表pandas分组:统计付款占比、累加数值及合并子项

修改方案

你原有代码的问题是分组时同时绑定了name和is_payed两个维度,无法统计单个用户的总订单数、付款占比这类全局指标,调整为仅按name分组,补充对应字段的聚合逻辑即可实现需求。

完整可运行代码

import pandas as pd

list1 = [{'name': 'maik','is_payed': 1, 'brand': 'HP', 'count': 1, 'items': [{'device': 'mouse', 'count': 110}]},{'name': 'milanie','is_payed': 0, 'brand': 'dell', 'count':10, 'items': [{'device': 'bales', 'count': 200}]}]
list2 = [{'name': 'maik','is_payed': 0, 'brand': 'HP', 'count': 20, 'items': [{'device': 'mouse', 'count': 1}]},{'name': 'nikola','is_payed': 1, 'brand': 'toshiba', 'count':10, 'items': [{'device': 'hard', 'count': 20}]}]
my_list= list1 + list2

final_list = []
# 仅按用户名分组
for user_name, user_group in pd.DataFrame(my_list).groupby('name'):
    # 计算付款占比
    total_order_cnt = len(user_group)
    payed_order_cnt = user_group['is_payed'].sum()
    # 合并所有商品明细
    all_items = []
    for item_list in user_group['items']:
        all_items.extend(item_list)
    # 同设备的count累加
    merged_items = pd.DataFrame(all_items).groupby('device', as_index=False)['count'].sum().to_dict('records')
    # 组装结果
    final_list.append({
        'name': user_name,
        'payed': payed_order_cnt / total_order_cnt,
        'brand': user_group['brand'].iloc[0],
        'count': user_group['count'].sum(),
        'items': merged_items
    })

# 输出结果
print(final_list)

运行结果

[
    {'name': 'maik', 'payed': 0.5, 'brand': 'HP', 'count': 21, 'items': [{'device': 'mouse', 'count': 111}]},
    {'name': 'milanie', 'payed': 0.0, 'brand': 'dell', 'count': 10, 'items': [{'device': 'bales', 'count': 200}]},
    {'name': 'nikola', 'payed': 1.0, 'brand': 'toshiba', 'count': 10, 'items': [{'device': 'hard', 'count': 20}]}
]

如果需要保留分数格式而非小数,可以引入fractions.Fraction处理payed字段的计算逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 02:06:08