【问题标题】:While using ExcelFile() I am getting ValueError: Invalid file path or buffer object type: <class 'pandas.core.frame.DataFrame'>使用 ExcelFile() 时出现 ValueError: Invalid file path or buffer object type: <class 'pandas.core.frame.DataFrame'>
【发布时间】:2019-11-10 23:08:47
【问题描述】:

这是我尝试过的代码。我正在尝试读取 excel 文件中存在的工作表,因此尝试了 ExcelFile(),但不确定为什么会出现以下错误。

# Import pandas
import pandas as pd
# Assign spreadsheet filename: file
xls = pd.read_excel('battledeath.xlsx')
# Load spreadsheet: xls
xls = pd.ExcelFile(pd.read_excel('battledeath.xls'))

我看到了这个错误:

ValueError                                Traceback (most recent call last)
<ipython-input-1-c639baabe58f> in <module>
      7 
      8 # Load spreadsheet: xls
----> 9 xls = pd.ExcelFile(pd.read_excel('battledeath.xls'))
     10 

C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\excel.py in __init__(self, io, **kwds)
    374             io = _urlopen(self._io)
    375         elif not isinstance(self.io, (ExcelFile, xlrd.Book)):
--> 376             io, _, _, _ = get_filepath_or_buffer(self._io)
    377 
    378         if engine == 'xlrd' and isinstance(io, xlrd.Book):

C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\common.py in get_filepath_or_buffer(filepath_or_buffer, encoding, compression, mode)
    216     if not is_file_like(filepath_or_buffer):
    217         msg = "Invalid file path or buffer object type: {_type}"
--> 218         raise ValueError(msg.format(_type=type(filepath_or_buffer)))
    219 
    220     return filepath_or_buffer, None, compression, False

ValueError: Invalid file path or buffer object type: <class 'pandas.core.frame.DataFrame'>

【问题讨论】:

    标签: python python-3.x pandas jupyter-notebook


    【解决方案1】:

    我认为您可能对read_excelExcelFile 之间的区别感到困惑,总而言之,一个是函数,如果需要,它会顺便为您创建一个ExcelFile 实例,另一个是一个类,但是,老实说,你真的不需要太担心这个。

    总之,你得到的错误正是它在锡上所说的,ExcelFile 很困惑你为什么将数据帧传递给它的构造函数。要解决您的问题,只需使用

    xls = pd.read_excel('battledeath.xlsx')
    

    现在,xls 是一个包含您的数据的数据框。另外,只是一个提示,阅读https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html

    【讨论】:

    • 谢谢丹尤尔。它对我有用。另外我想我可以简单地使用它,将熊猫导入为 pd file = 'battledeath.xlsx' xls = pd.ExcelFile(file) print(xls.sheet_names)
    猜你喜欢
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-07
    相关资源
    最近更新 更多