Check if pandas dataframe was passed to function

4.6k Views Asked by At

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().
3

There are 3 best solutions below

3
On BEST ANSWER

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
"""
3
On

You can say instead:

if df is None:

If you want to check for a dataframe contains data check:

if not df.empty:
0
On

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.