【问题标题】:Read Excel and convert it into a nested dictionary读取 Excel 并将其转换为嵌套字典
【发布时间】:2017-08-15 10:26:45
【问题描述】:

我有一个类似这样结构的 Excel 文件

name age status
anna 35 single
petr 27 married

有没有通用的方法可以将这样的 Excel 文件转换成这样结构的嵌套字典

{'anna': {'age':35}, {'status': 'single'}},
{'petr': {'age':27}, {'status': 'married'}}

我应该先导入一个 excel 文件并将其转换为 pandas 数据框,然后创建一个嵌套字典,还是存在导入 excel 表并创建这样一个字典的直接方法?

【问题讨论】:

    标签: python excel dictionary


    【解决方案1】:

    您要求的输出不是有效的 Python 数据结构。

    您可以使用df.to_dict 实现类似的效果:

    import pandas as pd
    
    df = pd.read_excel('path/to/file')
    df.set_index('name',  inplace=True)
    print(df.to_dict(orient='index'))
    # {'petr': {'age': 27, 'status': 'married'}, 'anna': {'age': 35, 'status': 'single'}}
    

    【讨论】:

    • 我已经编辑了输出,谢谢。您能否还告诉我如何按索引访问字典?例如,我调用 'petr' 它返回给我 {'age': 27, 'status': 'married'}?
    • @Ekaterina 字典有“键”,而不是“索引”。见docs.python.org/3.4/tutorial/datastructures.html#dictionaries
    • 是的,我知道,但是在运行“list(d.keys())”时,它会返回除“name”之外的所有键
    猜你喜欢
    • 2020-09-03
    • 2013-12-07
    • 2019-03-01
    • 1970-01-01
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多