Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pandas check if dataframe is not empty

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?

like image 953
Arthur Zangiev Avatar asked Apr 11 '16 08:04

Arthur Zangiev


People also ask

How do you check if a Pandas DataFrame is not empty?

To check if DataFrame is empty in Pandas, use pandas. DataFrame. empty attribute. This attribute returns a boolean value of true if this DataFrame is empty, or false if this DataFrame is not empty.

How check DataFrame is empty or not in python?

You can use the attribute df. empty to check whether it's empty or not: if df. empty: print('DataFrame is empty!

How do you know if a DF is empty?

Using len(df) or len(df. len() is a built-in function in python that gives the length (or the number of items) of a python object. If the length of a pandas dataframe or its index is zero, we can say that the dataframe is empty.

Is pandas DataFrame empty?

empty attribute checks if the dataframe is empty or not. It return True if the dataframe is empty else it return False .


2 Answers

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.

like image 144
Akshat Mahajan Avatar answered Sep 18 '22 13:09

Akshat Mahajan


.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.

like image 36
Santhosh Avatar answered Sep 20 '22 13:09

Santhosh