在 Python pandas 中将 xlsx 文件转换为字典

Posted

技术标签:

【中文标题】在 Python pandas 中将 xlsx 文件转换为字典【英文标题】:Converting an xlsx file to a dictionary in Python pandas 【发布时间】:2022-01-17 22:41:37 【问题描述】:

我正在尝试将 xlsx 文件中的数据框导入 Python,然后将此数据框转换为字典。这是我的 Excel 文件的样子:

  A B
1 a b
2 c d

其中 A 和 B 是列名,1 和 2 是行名。

我想使用 pandas 将数据框转换为 python 中的字典。我的代码很简单:

import pandas as pd
my_dict = pd.read_excel(‘.\inflation.xlsx’, sheet_name = ‘Sheet2’, index_col=0).to_dict()
print(my_dict)

我想要得到的是:

 ‘a’:’b’, ‘c’:’d’

但我得到的是:

‘b’:‘c’:’d’ 

可能是什么问题?

【问题讨论】:

【参考方案1】:

这符合要求:

import pandas as pd

d = pd.read_excel(‘.\inflation.xlsx’, sheet_name = ‘Sheet2’,index_col=0,header=None).transpose().to_dict('records')[0]
print(d)

输出:

'a': 'b', 'c': 'd'

to_dict() 函数采用orient 参数,该参数指定如何操作数据。如果您有更多行,还有其他选项。

【讨论】:

完美运行,谢谢! @besola 很高兴为您提供帮助(在 @BigBen 的协助下)。请勾选它作为已接受的答案,以指导其他人。【参考方案2】:

这应该可以工作

import pandas as pd
my_dict = pd.read_excel(‘.\inflation.xlsx’, sheet_name = ‘Sheet2’,header = 0 index_col=None).to_dict('records')
print(my_dict)

【讨论】:

正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center。

以上是关于在 Python pandas 中将 xlsx 文件转换为字典的主要内容,如果未能解决你的问题,请参考以下文章

Python使用pandas导入xlsx格式的excel文件内容

在 python 中将多个 excel '.xlsx' 转换为 '.csv' 文件时,我得到了额外的列?

在python脚本中将excel文件更改为csv?

如何使用 Python Pandas 将 CSV 文件写入 XLSX?

Python pandas数据框“日期”索引xlsx和csv中的不同格式

使用 win32com.client 模块在 Python 中将 .XLSX 转换为 .XLS