Reputation: 399
I have a function defined like this:
def demand_cleaning(df=None, location, output,_input,tables):
And I would like to test if df
was passed or not (df
is a pandas DataFrame
)
If df
is not passed I want to do something like
if df is None:
df = pd.read_pickle(tables + "Demand Raw")
But this test does not work now. and I get this
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Upvotes: 3
Views: 5029
Reputation: 14699
Something like this would do:
def g(var):
if isinstance(var, pd.DataFrame):
print("good to go")
else:
print("Nah!")
print(type(var))
a = None
b = pd.DataFrame()
print(g(a))
"""
output>>>
Nah!
<type 'NoneType'>
"""
print(g(b))
"""
output>>>
good to go
"""
Upvotes: 3
Reputation: 1858
Try to perform a type check directly:
if isinstance(df, pandas.DataFrame):
pass
Keep in mind, that the second argument of isinstance
depends on the namespace you have pandas imported into. This usually is pd
, which would yield to pd.DataFrame
.
Have a look at this article.
Upvotes: 4
Reputation: 3049
You can say instead:
if df is None:
If you want to check for a dataframe contains data check:
if not df.empty:
Upvotes: 8