Python 检查变量是否为数据框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14808945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:29:57  来源:igfitidea点击:

check if variable is dataframe

pythonpandas

提问by trbck

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

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

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.

我无法让它像预期的那样工作。

采纳答案by Jakub M.

Use isinstance, nothing else:

使用isinstance,没有别的:

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


PEP8says explicitly that isinstanceis the preferred way to check types

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

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()

isinstancehandles inheritance (see What are the differences between type() and isinstance()?). For example, it will tell you if a variable is a string (either stror unicode), because they derive from basestring)

isinstance处理继承(请参阅type() 和 isinstance() 之间的区别是什么?)。例如,它会告诉你一个变量是否是一个字符串(或者strunicode),因为它们派生自basestring)

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

Specifically for pandasDataFrameobjects:

专门针对pandasDataFrame对象:

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

回答by Rutger Kassies

Use the built-in isinstance()function.

使用内置isinstance()函数。

import pandas as pd

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