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

如何利用DataFrame三列生成指定结构的嵌套字典:以Column1为键,Column2与Integer列组成的字典为值

解决方案:将DataFrame转换为嵌套字典

嘿,这个需求其实很常见,我给你两种实用的方法,你可以根据自己的场景来选:

方法1:用pandas原生方法快速实现(最推荐)

这是最简洁高效的方式,利用pandas的groupby和to_dict组合就能一步到位:

先构造你给出的示例DataFrame方便测试:

import pandas as pd

df = pd.DataFrame({
    'Column1': ['Apple', 'Apple', 'Apple', 'Strawberry'],
    'Column2': ['Orange', 'Pineapple', 'Juice', 'Raspberry'],
    'Integer': [5, 10, 3, 11]
})

然后执行转换代码:

result_dict = df.groupby('Column1').apply(lambda x: x.set_index('Column2')['Integer'].to_dict()).to_dict()

运行后result_dict就是你想要的结构:

{
    'Apple': {'Orange': 5, 'Pineapple': 10, 'Juice': 3},
    'Strawberry': {'Raspberry': 11}
}

代码简单解释:

  • groupby('Column1'):把相同Column1值的行归为一组
  • apply(lambda x: ...):对每个分组,将Column2设为索引,再把Integer列转成以索引为键的字典
  • 最后to_dict()把分组结果转成外层字典

方法2:手动遍历行(适合理解底层逻辑)

如果想搞清楚每一步的操作逻辑,可以手动遍历DataFrame的行来构建字典:

result_dict = {}
for _, row in df.iterrows():
    # 提取当前行的三个值
    outer_key = row['Column1']
    inner_key = row['Column2']
    value = row['Integer']
    
    # 外层键不存在时,先创建对应的内层空字典
    if outer_key not in result_dict:
        result_dict[outer_key] = {}
    # 向内层字典添加键值对
    result_dict[outer_key][inner_key] = value

这个方法逻辑直观,适合刚接触pandas的朋友理解转换过程,最终结果和方法1完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 14:17:39