+4 votes
in Programming Languages by (22.6k points)
I need to read several dataframes at runtime. If the dataframe is empty, the code needs to skip processing it. How can I check if the dataframe is empty?

1 Answer

+2 votes
by (42.1k points)

There are several ways to find whether or not a given pandas DataFrame is empty.

Here I am declaring two DataFrames, df and df1, for testing.

>>> import pandas as pd
>>> df = pd.DataFrame({'a':np.random.random(3), 'b':np.random.random(3), 'c':np.random.random(3)})
>>> df
          a         b         c
0  0.546561  0.904433  0.669987
1  0.265768  0.240396  0.358043
2  0.631672  0.871593  0.731576
>>> df1=pd.DataFrame()

  • Using attribute 'empty'

It will return True if the DataFrame is empty; otherwise, False.

>>> import pandas as pd
>>> df.empty
False
>>> df1.empty
True

  • Using attribute 'size'

If the returned value is 0, the DataFrame is empty.

>>> df.size
9
>>> df1.size
0

  • Using attribute 'shape'

If the returned value is (0,0), the DataFrame is empty.

>>> df.shape
(3, 3)
>>> df1.shape
(0, 0)

...