首页 > 解决方案 > 将数据框转换为具有键和多个值的字典

问题描述

我有一个用例,我必须读取具有多个标题列和值的 xl 文件。

I have to convert that into a dictionary, key with multiple values.
The xl header will vary each time, some times 2 columns some to three, and so on.

The sample data frame for an xl file is
      key1    key2
      abc     xyz
      bca     yxz
      cab     zxy

the output should be as...
   {'key1': ['abc','bca','cab'], 'key2': ['xyz','yxz', 'zxy']}

if there is one more column key3, I should able to include that as well in the dictionary

.

import pandas as pd
workbook_loc = "c:\\2020\Book1.xlsx"
df = pd.read_excel(workbook_loc, sheet_name=None)
data_dict = df.to_dict()

but the above script is throwing out  AttributeErro 'dict' object has no attribute.

what is the wrong I am doing?

标签: python-3.xpandas

解决方案


当您指定sheet_name=None时,它​​会返回字典而不是 pandas 数据框。指定工作表名称始终是一种好习惯。

你可以试试这个。。

import pandas as pd
workbook_loc = "c:\\2020\Book1.xlsx"
df = pd.read_excel(workbook_loc, index_col=0, sheet_name='Sheet1')
data_dict = {}
for col in df.columns:
    data_dict[col]=[row for row in df[col]]

推荐阅读