【问题标题】:TypeError: expected str, bytes or os.PathLike object, not DataFrame - Not a RepostTypeError:预期的 str、bytes 或 os.PathLike 对象,而不是 DataFrame - 不是 Repost
【发布时间】:2020-10-28 17:45:35
【问题描述】:

这个问题的另一个版本没有得到回答,原始发布者没有给出他们代码的完整示例......

我有一个用于导入电子表格以进行格式化的函数。现在,电子表格可以有两种形式:

  1. 作为要作为 DataFrame 导入的文件名字符串(excel、.csv 等)
  2. 直接作为 DataFrame(还有另一个函数可能会或可能不会被调用来进行一些预处理)

代码看起来像

def func1(spreadsheet):
    if type(spreadsheet) == pd.DataFrame: 
        df = spreadsheet
    else:
        df_ext = os.path.splitext(spreadsheet)[1]
        etc. etc.

如果我使用 DataFrame 运行此函数,我会收到以下错误:

---> 67     if type(spreadsheet) == pd.DataFrame: df = spreadsheet
     68     else:

/opt/anaconda3/lib/python3.7/posixpath.py in splitext(p)
    120 
    121 def splitext(p):
--> 122     p = os.fspath(p)
    123     if isinstance(p, bytes):
    124         sep = b'/'

TypeError: expected str, bytes or os.PathLike object, not DataFrame

为什么要这样做?

【问题讨论】:

  • 我试过了。它抛出了同样的错误......

标签: python pandas dataframe


【解决方案1】:

因此,一种方法是仅与字符串进行比较并在 else 条件下读取数据帧。 另一种方法是使用isinstance

In [21]: dict1
Out[21]: {'a': [1, 2, 3, 4], 'b': [2, 4, 6, 7], 'c': [2, 3, 4, 5]}

In [24]: df = pd.DataFrame(dict1)

In [28]: isinstance(df, pd.DataFrame)
Out[28]: True

In [30]: isinstance(os.getcwd(), pd.DataFrame)
Out[30]: False

所以,在你的情况下,就这样做

if isinstance(spreadsheet, pd.DataFrame)

【讨论】:

  • 我尝试将 if 语句切换为 'if type(spreadsheet) == str:...' 但它抛出了完全相同的错误!!
  • 即使我只是尝试 'print(type(spreadsheet))' 看看发生了什么,它也会抛出错误
【解决方案2】:

这行是问题所在:

if type(spreadsheet) == pd.DataFrame: 

数据帧的类型是pandas.core.frame.DataFramepandas.DataFrame is a class 当你调用它时返回一个数据框。

其中任何一个都可以:

if type(spreadsheet) == type(pd.DataFrame()):


if type(spreadsheet) == pd.core.frame.DataFrame:

【讨论】:

  • 如果我在函数之外执行 'type(spreadsheet) == pd.DataFrame',它会返回 True。我试过你修复,但它返回了同样的错误
猜你喜欢
  • 1970-01-01
  • 2022-01-17
  • 2019-11-15
  • 2018-11-08
  • 2018-11-11
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多