python - 无法使用 pandas 读取 excel 文件的所有工作表

标签 python python-3.x excel pandas list

该程序适用于读取 excel 文件的第一张表,而我试图读取 excel 文件的所有表,但我无法读取所有表。

python
而我添加sheet_name = None在阅读 excel 行
我收到这样的错误我无法找出错误是什么以及如何纠正错误。
(scrap-3-HFZx_P-py3.9) PS F:\mohan> & C:/Users/hp/AppData/Local/pypoetry/Cache/virtualenvs/scrap-3-HFZx_P-py3.9/Scripts/python.exe f:/mohan/main.py
ENTER THE LIST HERE : userid,city,state
enter the full path to the file : F:\\mis\\KB.xlsx
Traceback (most recent call last):
  File "f:\mohan\main.py", line 16, in <module>     
    print(obj.extract(file_name))
  File "f:\mohan\main.py", line 9, in extract       
    return raw_excel[conf].to_dict(orient='records')
TypeError: unhashable type: 'list'

最佳答案

解决方案:

#output is nested lists of list of dictionaries
def extract(self, file_name):
    raw_excel=pd.read_excel(file_name,sheet_name=None)
    return [v[v.columns.intersection(conf)].to_dict(orient='records')
                  for k, v in raw_excel.items()]
解释 :
如果使用 sheet_name=None输出是 DataFrames 的字典,这里是 raw_excel .
如果此处需要通过 dict 循环,则使用列表理解和方法 items , 所以 vvalue s 和 k对于 key s。
如果存在于 conf 中,则仅过滤来自 DataFrame 的列使用 Index.intersection .
最后使用 to_dict ,因此获取每个 DataFrame 的字典列表。最终输出,换句话说 return获取字典列表的列表。
如果需要展平输出,可以使用 this solution :
flat_list = [item for sublist in t for item in sublist]
所以代码被改变了:
#output is flatten list of dictionaries
def extract(self, file_name):
    raw_excel=pd.read_excel(file_name,sheet_name=None)
    return [x for k, v in raw_excel.items() 
               for x in v[v.columns.intersection(conf)].to_dict(orient='records')]

关于python - 无法使用 pandas 读取 excel 文件的所有工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70662405/

相关文章:

c# - 运行 Excel 加载项时,如果我之前的运行以断点结束,我总是会收到错误

vba - Excel 2013 - VBA - 创建和访问 [超过 4 个!] 条件格式项目时出现运行时错误 9

vba - 将带有路径的excel文件中的列导入数组

python - 在scrapy中提取类名

python - 在 jupyter notebook 中加载 spacy 时出现 ImportError

python - 使用 python pandas 查找另一个数据框并返回相应的值

python-3.x - grab_set() 函数在 tkinter 中不起作用

python - 为什么使用 PIL 会出现颜色量化伪影?

python - 如何在django中将文件保存到数据库

python - 如果窗口大小调整,则调整窗口小部件的大小