如何利用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
相关产品推荐
相关产品推荐

