Python pandas check if dataframe is not empty

PythonPython 3.xPandas

Python Problem Overview


I have an if statement where it checks if the data frame is not empty. The way I do it is the following:

if dataframe.empty:
    pass
else:
    #do something

But really I need:

if dataframe is not empty:
    #do something

My question is - is there a method .not_empty() to achieve this? I also wanted to ask if the second version is better in terms of performance? Otherwise maybe it makes sense for me to leave it as it is i.e. the first version?

Python Solutions


Solution 1 - Python

Just do

if not dataframe.empty:
     # insert code here

The reason this works is because dataframe.empty returns True if dataframe is empty. To invert this, we can use the negation operator not, which flips True to False and vice-versa.

Solution 2 - Python

.empty returns a boolean value

>>> df_empty.empty
True

So if not empty can be written as

if not df.empty:
    #Your code

Check pandas.DataFrame.empty , might help someone.

Solution 3 - Python

You can use the attribute dataframe.empty to check whether it's empty or not:

if not dataframe.empty:
    #do something

Or

if len(dataframe) != 0:
   #do something

Or

if len(dataframe.index) != 0:
   #do something

Solution 4 - Python

Another way:

if dataframe.empty == False:
    #do something`

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArthur ZangievView Question on Stackoverflow
Solution 1 - PythonAkshat MahajanView Answer on Stackoverflow
Solution 2 - PythonSanthoshView Answer on Stackoverflow
Solution 3 - PythonRajarshi DasView Answer on Stackoverflow
Solution 4 - PythonArjunView Answer on Stackoverflow