问题:检查变量是否为数据框

当我的函数f用一个变量调用时,我想检查var是否是一个熊猫数据框:

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

我想解决方案可能很简单,但即使

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

我无法使其按预期方式工作。

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.


回答 0

使用isinstance,没有别的:

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

PEP8明确表示这isinstance是检查类型的首选方法

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

而且甚至不用考虑

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

isinstance处理继承(请参见type()和isinstance()之间的区别?)。例如,它会告诉你,如果一个变量是一个字符串(strunicode),因为他们从派生basestring

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

专门针对pandas DataFrame对象:

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

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 What are the differences between type() and isinstance()?). 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)

回答 1

使用内置isinstance()功能。

import pandas as pd

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

Use the built-in isinstance() function.

import pandas as pd

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。