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

如何将Pandas DataFrame列转换为指定格式的字典?

便捷实现方法

以下是几种高效的实现方式,其中Pandas原生分组方法最便捷:

  • 方法1:groupby + to_dict(推荐)
    利用Pandas的groupby按姓名分组,将每组的Age列转为列表后直接转成字典,一行代码完成:

    import pandas as pd
    df = pd.DataFrame({'Name': ['John', 'John', 'Sara', 'Sara', 'Sara', 'Peter', 'Peter'],
                        'Age': [11, 22, 33, 44, 55, 66, 77]})
    
    out_dict = df.groupby('Name')['Age'].apply(list).to_dict()
    print(out_dict)
    # 输出:{'John': [11, 22], 'Peter': [66, 77], 'Sara': [33, 44, 55]}
    
  • 方法2:字典推导式
    遍历分组后的结果,用字典推导式直接构建目标字典,逻辑直观:

    out_dict = {name: group['Age'].tolist() for name, group in df.groupby('Name')}
    
  • 方法3:普通循环
    适合理解基础逻辑,手动遍历每行构建字典,效率低于前两种方法:

    out_dict = {}
    for _, row in df.iterrows():
        name = row['Name']
        age = row['Age']
        out_dict.setdefault(name, []).append(age)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 16:24:46