check if variable is dataframe

PythonPandas

Python Problem Overview


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

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

I guess the solution might be quite simple but even with

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

I can't get it to work like expected.

Python Solutions


Solution 1 - Python

Use isinstance, nothing else:

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

PEP8 says explicitly that isinstance is the preferred way to check types

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 https://stackoverflow.com/questions/1549801/differences-between-isinstance-and-type-in-python). For example, it will tell you if a variable is a string (either str or unicode), because they derive from basestring)

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

Specifically for pandas DataFrame objects:

import pandas as pd
isinstance(var, pd.DataFrame)

Solution 2 - Python

Use the built-in isinstance() function.

import pandas as pd

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontrbckView Question on Stackoverflow
Solution 1 - PythonJakub M.View Answer on Stackoverflow
Solution 2 - PythonRutger KassiesView Answer on Stackoverflow