How to check whether a pandas DataFrame is empty?

前端 未结 5 825
别跟我提以往
别跟我提以往 2020-12-02 04:01

How to check whether a pandas DataFrame is empty? In my case I want to print some message in terminal if the DataFrame is empty.

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 04:57

    1) If a DataFrame has got Nan and Non Null values and you want to find whether the DataFrame
    is empty or not then try this code.
    2) when this situation can happen? 
    This situation happens when a single function is used to plot more than one DataFrame 
    which are passed as parameter.In such a situation the function try to plot the data even 
    when a DataFrame is empty and thus plot an empty figure!.
    It will make sense if simply display 'DataFrame has no data' message.
    3) why? 
    if a DataFrame is empty(i.e. contain no data at all.Mind you DataFrame with Nan values 
    is considered non empty) then it is desirable not to plot but put out a message :
    Suppose we have two DataFrames df1 and df2.
    The function myfunc takes any DataFrame(df1 and df2 in this case) and print a message 
    if a DataFrame is empty(instead of plotting):
    df1                     df2
    col1 col2           col1 col2 
    Nan   2              Nan  Nan 
    2     Nan            Nan  Nan  
    

    and the function:

    def myfunc(df):
      if (df.count().sum())>0: ##count the total number of non Nan values.Equal to 0 if DataFrame is empty
         print('not empty')
         df.plot(kind='barh')
      else:
         display a message instead of plotting if it is empty
         print('empty')
    

提交回复
热议问题