【问题标题】:Importing excel file in Pandas Gives Error在 Pandas 中导入 excel 文件会出错
【发布时间】:2017-04-04 11:54:06
【问题描述】:

您好,很抱歉打扰,但我在导入 excel 文件时遇到了一些重大问题,我希望有人能给我一些建议,我已经尝试了以前在 stackflow 上发布的各种方法,但似乎都没有工作。

import pandas as pd

# making an excel data sheet
df = pd.DataFrame({'Dox Dossage': [1,5,10,100,500,1000], 'MP': [7,35,70,700,3500,7000]})
writer = pd.ExcelWriter('Michael4-3-17', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()

抓取excel文件并在excel中打开

import glob
print(glob.glob('Michael4-3-17*'))
graphfile = glob.glob('Michael4-3-17*')
df1 = pd.read_excel(open(graphfile), sheetname=None)

我不断收到的错误是:

--> 4 df1 = pd.read_excel(open(graphfile), sheetname=None)

TypeError: 预期的 str、bytes 或 os.PathLike 对象,而不是列表

【问题讨论】:

  • 这里使用glob的目的是什么?
  • graphfile 似乎是文件路径列表。也很确定你在使用pd.read_excel时不需要指定open

标签: python excel


【解决方案1】:

在我看来有两个问题:(1) 使用 glob,你会得到一个列表,(2) 使用 open(graphfile),你没有传递文件名。你可以通过这样做来简化很多:

graphfile = 'Michael4-3-17.xlsx'
df1 = pd.read_excel(graphfile, sheetname=None)

但也许您正在使用 glob,因为您有多个文件,在这种情况下您可以这样做(我有两个文件,Micahael4-3-17 有和没有 xlsx 扩展名):

import glob
print(glob.glob('Michael4-3-17*'))
graphfile = glob.glob('Michael4-3-17*')
for file in graphfile:
    df1 = pd.read_excel(file, sheetname=None)
    print(df1)

产生:

['Michael4-3-17', 'Michael4-3-17.xlsx']
{'Sheet1':    Dox Dossage    MP
0            1     7
1            5    35
2           10    70
3          100   700
4          500  3500
5         1000  7000}
{'Sheet1':    Dox Dossage    MP
0            1     7
1            5    35
2           10    70
3          100   700
4          500  3500
5         1000  7000}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-18
    • 2013-10-18
    • 1970-01-01
    • 2021-12-01
    • 2015-05-27
    • 2019-08-08
    • 2019-07-18
    • 1970-01-01
    相关资源
    最近更新 更多