You can use df.empty to check if a Pandas DataFrame is empty:
df = df.empty
Where:
- “True” means that the DataFrame is empty
- “False” means that the DataFrame is not empty
Steps to Check if a Pandas DataFrame is Empty
Step 1: Create a DataFrame
To start with a simple example, let’s create a DataFrame with 2 columns:
import pandas as pd boxes = {'Color': ['Blue','Blue','Green','Green','Red','Red'], 'Height': [15,20,25,20,15,25] } df = pd.DataFrame(boxes, columns = ['Color','Height']) print (df)
Run the code in Python, and you’ll see the following DataFrame:
Step 2: Check if the DataFrame is Empty
Next, check if the DataFrame is empty by adding the following syntax:
df = df.empty
Therefore, the complete Python code is:
import pandas as pd boxes = {'Color': ['Blue','Blue','Green','Green','Red','Red'], 'Height': [15,20,25,20,15,25] } df = pd.DataFrame(boxes, columns = ['Color','Height']) df = df.empty print (df)
Once you run the code, you’ll get “False” which means that the DataFrame is not empty:
Step 3: Drop all Columns in the DataFrame
Let’s now drop all the columns in the DataFrame using this syntax:
df = df.drop(['Color','Height'],axis=1)
Here is the complete Python code to drop all the columns, and then check if the DataFrame is empty:
import pandas as pd boxes = {'Color': ['Blue','Blue','Green','Green','Red','Red'], 'Height': [15,20,25,20,15,25] } df = pd.DataFrame(boxes, columns = ['Color','Height']) df = df.drop(['Color','Height'],axis=1) df = df.empty print (df)
You’ll then get “True” which means that the DataFrame is Empty:
Dealing with NaNs
Let’s create a DataFrame that consists only NaN values:
import pandas as pd import numpy as np data = {'first_column': [np.nan,np.nan,np.nan,np.nan,np.nan,np.nan], 'second_column': [np.nan,np.nan,np.nan,np.nan,np.nan,np.nan] } df = pd.DataFrame(data,columns=['first_column','second_column']) print (df)
As you can see, the DataFrame consists only NaNs:
Next, check if the DataFrame is empty:
import pandas as pd import numpy as np data = {'first_column': [np.nan,np.nan,np.nan,np.nan,np.nan,np.nan], 'second_column': [np.nan,np.nan,np.nan,np.nan,np.nan,np.nan] } df = pd.DataFrame(data,columns=['first_column','second_column']) df = df.empty print (df)
You’ll get “False” which means that the DataFrame is not empty, even if it consists only NaNs:
You can drop the NaN values using dropna:
df = df.dropna()
Let’s drop all the NaN values in the DataFrame, and then check again if the DataFrame is empty:
import pandas as pd import numpy as np data = {'first_column': [np.nan,np.nan,np.nan,np.nan,np.nan,np.nan], 'second_column': [np.nan,np.nan,np.nan,np.nan,np.nan,np.nan] } df = pd.DataFrame(data,columns=['first_column','second_column']) df = df.dropna() df = df.empty print (df)
As you can see, the DataFrame is indeed empty after dropping the NaNs:
You can check the Pandas Documentation to learn more about df.empty.