check if variable is dataframe

前端 未结 2 1567
终归单人心
终归单人心 2020-12-04 09:56

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         


        
相关标签:
2条回答
  • 2020-12-04 10:29

    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)
    
    0 讨论(0)
  • 2020-12-04 10:29

    Use the built-in isinstance() function.

    import pandas as pd
    
    def f(var):
        if isinstance(var, pd.DataFrame):
            print("do stuff")
    
    0 讨论(0)
提交回复
热议问题