You can use the following syntax to check if a pandas DataFrame is empty:
len(df.index) == 0
This particular syntax checks if the length of the index column in the DataFrame is equal to zero, which is equivalent to checking if the entire DataFrame is empty.
If the DataFrame is empty, this syntax will return True. Otherwise, it will return False.
If you would like to print custom text that tells you whether a DataFrame is empty, you can use a simple if else function:
if len(df.index) == 0:
print('df is empty')
else:
print('df is not empty')
The following example shows how to use these functions in practice.
Example: Check if Pandas DataFrame is Empty
Suppose we have the following empty pandas DataFrame:
import pandas as pd #create empty DataFrame df = pd.DataFrame(columns=['A', 'B', 'C', 'D', 'E']) #view DataFrame print(df) Empty DataFrame Columns: [A, B, C, D, E] Index: []
We can use the following code to check if the pandas DataFrame is empty:
#check if DataFrame is empty len(df.index) == 0 True
The function returns True, which tells us that the DataFrame is indeed empty.
We could also use the following code to print custom text that tells us whether or not the DataFrame is empty:
#check if DataFrame is empty and return output
if len(df.index) == 0:
print('df is empty')
else:
print('df is not empty')
df is empty
The output tells us that the DataFrame is empty.
By contrast, suppose we have a DataFrame that is not empty:
import pandas as pd #create DataFrame df_full = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], 'points': [18, 22, 19, 14, 14, 11, 20, 28], 'assists': [5, 7, 7, 9, 12, 9, 9, 4], 'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]}) #view DataFrame print(df_full) team points assists rebounds 0 A 18 5 11 1 B 22 7 8 2 C 19 7 10 3 D 14 9 6 4 E 14 12 6 5 F 11 9 5 6 G 20 9 9 7 H 28 4 12
We can use the len() function to check if the DataFrame is empty:
#check if DataFrame is empty len(df_full.index) == 0 False
The function returns False, which tells us that the DataFrame is not empty.
And if we use an if else function, we can return custom output:
#check if DataFrame is empty and return output
if len(df_full.index) == 0:
print('df is empty')
else:
print('df is not empty')
df is not empty
The output tells us that the DataFrame is not empty.
Additional Resources
The following tutorials explain how to perform other common operations in pandas:
How to Check if Cell is Empty in Pandas DataFrame
How to Get Cell Value in Pandas DataFrame
How to Create Empty Pandas DataFrame with Column Names