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

如何在Pandas中按列名条件聚合数据生成指定字典结构?

解决方案

步骤1:筛选目标列

先提取所有以is_开头的列,解决你提到的列筛选瓶颈:

is_cols = [col for col in df.columns if col.startswith('is_')]

步骤2:分组聚合生成目标字典

按language分组后,遍历目标列收集对应为True的id列表,只保留非空的结果:

result = {}
for lang, group in df.groupby('language'):
    lang_sub_dict = {}
    for col in is_cols:
        valid_ids = group[group[col] == True]['id'].tolist()
        if valid_ids:
            lang_sub_dict[col] = valid_ids
    result[lang] = lang_sub_dict

最终输出结果

运行后result即为你需要的结构:

{
  "de" :{"is_bruiser" : [121,1542], "is_tank" : [121,542]},
  "fr": {"is_bruiser" : [1216,4578] } 
}

简洁写法(可选)

用嵌套字典推导式压缩代码:

is_cols = [col for col in df.columns if col.startswith('is_')]
result = {
    lang: {
        col: group[group[col]]['id'].tolist()
        for col in is_cols
        if not group[group[col]]['id'].empty
    }
    for lang, group in df.groupby('language')
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 10:42:30