我有一个 Excel 文件,其结构如下:
name age status
anna 35 single
petr 27 married
我已将这样的文件转换为结构如下的嵌套字典:
{'anna': {'age':35}, {'status': 'single'}},
{'petr': {'age':27}, {'status': 'married'}}
使用 Pandas :
import pandas as pd
df = pd.read_excel('path/to/file')
df.set_index('name', inplace=True)
print(df.to_dict(orient='index'))
但是现在运行 list(df.keys())
时,它会返回字典中所有键的列表(“年龄”、“状态”等),但不返回“名称”。
我的最终目标是它通过输入名称返回所有键和值。
有可能吗?或者也许我应该使用其他方式导入数据以实现目标?最终我无论如何都应该找到一本字典,因为我将通过一个键将它与其他字典合并。
最佳答案
我认为您需要将参数drop=False
设置为set_index
对于不删除列名称
:
import pandas as pd
df = pd.read_excel('path/to/file')
df.set_index('name', inplace=True, drop=False)
print (df)
name age status
name
anna anna 35 single
petr petr 27 married
d = df.to_dict(orient='index')
print (d)
{'anna': {'age': 35, 'status': 'single', 'name': 'anna'},
'petr': {'age': 27, 'status': 'married', 'name': 'petr'}}
print (list(df.keys()))
['name', 'age', 'status']
关于python - 获取按索引定向的嵌套字典中的键和值列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45694706/