Check if the variable is dataframe

when my f function is called with a variable, I want to check if var is a pandas data array:

def f(var): if var == pd.DataFrame(): print "do stuff" 

I think the solution can be quite simple, but even with

 def f(var): if var.values != None: print "do stuff" 

I can't get it to work as expected.

+74
python pandas
Feb 11 '13 at 9:10
source share
2 answers

Use isinstance , nothing more:

 if isinstance(x, pd.DataFrame): ... # do something 



PEP8 explicitly says that isinstance is the preferred type checking method

 No: type(x) is pd.DataFrame No: type(x) == pd.DataFrame Yes: isinstance(x, pd.DataFrame) 

And don't even think about

 if obj.__class__.__name__ = 'DataFrame': expect_problems_some_day() 

isinstance handles inheritance (see what are the differences between type () and isinstance ()? ). For example, it will tell you if the variable is a string ( str or unicode ), because they are derived from basestring )

 if isinstance(obj, basestring): i_am_string(obj) 

Especially for pandas DataFrame objects:

 import pandas as pd isinstance(var, pd.DataFrame) 
+61
Feb 11 '13 at 9:23
source share

Use the built-in isinstance() .

 import pandas as pd def f(var): if isinstance(var, pd.DataFrame): print("do stuff") 
+122
Feb 11 '13 at 9:15
source share



All Articles