检查变量是否为数据框 [英] check if variable is dataframe
问题描述
当我的函数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()?).例如,它将告诉您变量是否为字符串(str
或unicode
),因为它们是从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屋!