Testing if a pandas DataFrame exists

前端 未结 2 1392
有刺的猬
有刺的猬 2021-02-03 17:44

In my code, I have several variables which can either contain a pandas DataFrame or nothing at all. Let\'s say I want to test and see if a certain DataFrame has been created ye

2条回答
  •  名媛妹妹
    2021-02-03 17:55

    In my code, I have several variables which can either contain a pandas DataFrame or nothing at all

    The Pythonic way of indicating "nothing" is via None, and for checking "not nothing" via

    if df1 is not None:
        ...
    

    I am not sure how critical time is here, but since you measured things:

    In [82]: t = timeit.Timer('if x is not None: pass', setup='x=None')
    
    In [83]: t.timeit()
    Out[83]: 0.022536039352416992
    
    In [84]: t = timeit.Timer('if isinstance(x, type(None)): pass', setup='x=None')
    
    In [85]: t.timeit()
    Out[85]: 0.11571192741394043
    

    So checking that something is not None, is also faster than the isinstance alternative.

提交回复
热议问题