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.
You can use the attribute df. empty to check whether it's empty or not: if df. empty: print('DataFrame is empty!
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.
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.
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.
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
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 '''
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With