check if variable is dataframe

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.


isinstance, nothing else.

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

Yes: if isinstance(obj, int):
No:  if type(obj) is type(1):

And don't even think about

if obj.__class__.__name__ = "MyInheritedClass":
    expect_problems_some_day()

isinstance handles inheritance (see 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)

使用内置的isinstance()函数。

import pandas as pd

def f(var):
    if isinstance(var, pd.DataFrame):
        print "do stuff"
链接地址: http://www.djcxy.com/p/54232.html

上一篇: Python检查列表中的所有元素是否是相同的类型

下一篇: 检查变量是否是数据帧