python-3.x - 将数据框转换为具有键和多个值的字典
问题描述
我有一个用例,我必须读取具有多个标题列和值的 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?
解决方案
当您指定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]]
推荐阅读
- c# - 如何在 Windows 10(10 月更新)中获取剪贴板历史记录?
- php - Laravel 5.2 在用户注册时上传图片到上传文件夹
- linux - 如果文件在linux的子目录中不存在,则检索父目录名称的命令
- python - 如何使用 Sympys NumPyPrinter?
- git - 尝试克隆存储库时出现 Git 认证错误
- vega-lite - 在 VegaEmbed 中更新数据的最简单方法
- c# - Lucene 批量 Udate 问题
- sql - Oracle - 选择所需列仅包含一种特定类型数据的行
- c# - 使用 .NET 更新 SSAS 表格模型的 M 表达式时未保存到数据库的更改
- php - 无法理解 preg_match_all()