检查变量是否为数据框 [英] check if variable is dataframe

查看:95
本文介绍了检查变量是否为数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 ,仅此而已:

Use isinstance, nothing else:

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


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


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)

甚至不要考虑

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

isinstance处理继承(请参见> type()之间有什么区别?和isinstance()?).例如,它将告诉您变量是否为字符串(strunicode),因为它们是从basestring派生的)

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)

专门用于pandas DataFrame对象:

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

这篇关于检查变量是否为数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆