python - 获取按索引定向的嵌套字典中的键和值列表

标签 python excel pandas dictionary

我有一个 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/

相关文章:

python - 获取 Django 模型字段的 Python 类型?

python - 我可以用 Python/OpenCV 复制 GIMP 的 HSL 复合函数吗?

python - 优化对象显示(gamedev)

python - 使用 pandas 数据框中最近创建的属性来创建新属性

python - 将 read_excel 与转换器一起使用以将 Excel 文件读入 Pandas DataFrame 会导致对象类型的数字列

python - 从Python中的特定月份开始按年月填充日期列

php - 如何在php中设置条件css

excel - 在 Excel 中将 A 列中的所有 @提及和 #hashtags 复制到 B 列和 C 列

添加 VBA(从其他工作表中提取数据)例程后 Excel 文件变得太重

python - 如何将Python列表转换为pandas DataFrame :