Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a pandas DataFrame is empty?

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.

like image 675
Nilani Algiriyage Avatar asked Nov 07 '13 05:11

Nilani Algiriyage


People also ask

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

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 data frame is empty or none?

empty attribute checks if the dataframe is empty or not. It return True if the dataframe is empty else it return False . Example #1: Use DataFrame. empty attribute to check if the given dataframe is empty or not.

How do you check if a DataFrame column is empty?

If our dataframe is empty it will return 0 at 0th index i.e. the count of rows. So, we can check if dataframe is empty by checking if value at 0th index is 0 in this tuple.

Is not empty in Pandas?

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.


2 Answers

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

if df.empty:     print('DataFrame is empty!') 

Source: Pandas Documentation

like image 82
aIKid Avatar answered Sep 28 '22 05:09

aIKid


I use the len function. It's much faster than empty. len(df.index) is even faster.

import pandas as pd import numpy as np  df = pd.DataFrame(np.random.randn(10000, 4), columns=list('ABCD'))  def empty(df):     return df.empty  def lenz(df):     return len(df) == 0  def lenzi(df):     return len(df.index) == 0  ''' %timeit empty(df) %timeit lenz(df) %timeit lenzi(df)  10000 loops, best of 3: 13.9 µs per loop 100000 loops, best of 3: 2.34 µs per loop 1000000 loops, best of 3: 695 ns per loop  len on index seems to be faster ''' 
like image 38
Zero Avatar answered Sep 28 '22 07:09

Zero