[英]TypeError: expected str, bytes or os.PathLike object, not DataFrame - Not a Repost
The other version of this question wasn't ever answered, the original poster didn't give a full example of their code...这个问题的另一个版本从未得到回答,原始海报没有给出他们代码的完整示例......
I have a function that's meant to import a spreadsheet for formatting purposes.我有一个用于导入电子表格以进行格式化的函数。 Now, the spreadsheet can come in two forms:
现在,电子表格可以有两种形式:
the code looks like代码看起来像
def func1(spreadsheet):
if type(spreadsheet) == pd.DataFrame:
df = spreadsheet
else:
df_ext = os.path.splitext(spreadsheet)[1]
etc. etc.
If I run this function with a DataFrame, I get the following error:如果我使用 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
Why is it doing this?为什么要这样做?
So, one way is to just compare with a string and reading the dataframe in the else condition.因此,一种方法是仅与字符串进行比较并在 else 条件下读取数据帧。 The other way would be to use
isinstance
另一种方法是使用
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
So, in your case just do this所以,在你的情况下就这样做
if isinstance(spreadsheet, pd.DataFrame)
This line is the problem:这一行是问题:
if type(spreadsheet) == pd.DataFrame:
The type of a dataframe is pandas.core.frame.DataFrame
.数据帧的类型是
pandas.core.frame.DataFrame
。 pandas.DataFrame is a class which returns a dataframe when you call it. pandas.DataFrame 是一个在调用时返回数据帧的类。
Either of these would work:这些中的任何一个都可以工作:
if type(spreadsheet) == type(pd.DataFrame()):
if type(spreadsheet) == pd.core.frame.DataFrame:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.