Reputation: 154
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:
---> 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?
Upvotes: 0
Views: 2740
Reputation: 9091
This line is the problem:
if type(spreadsheet) == pd.DataFrame:
The type of a dataframe is pandas.core.frame.DataFrame
. pandas.DataFrame is a class which returns a dataframe when you call it.
Either of these would work:
if type(spreadsheet) == type(pd.DataFrame()):
if type(spreadsheet) == pd.core.frame.DataFrame:
Upvotes: 1
Reputation: 1215
So, one way is to just compare with a string and reading the dataframe in the else condition.
The other way would be to use 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)
Upvotes: 2