In this tutorial, we will learn how to find if a Pandas dataframe is empty or not. Pandas empty method applied to a Pandas dataframe will tell us if the dataframe is empty or not. Pandas’ empty method will return True if the dataframe is empty and False otherwise.
Let us see some examples of using Pandas empty method. First we will load Pandas.
import pandas as pd
Applying Pandas empty method on non-empty dataframe
Here we create toy dataframe with some data in it.
df1 = pd.DataFrame({"col1":["A","B","C"], "col2":[1,2,3]})
We can see that our dataframe is not empty.
df1 col1 col2 0 A 1 1 B 2 2 C 3
And apply Pandas empty method on this dataframe we should get False as result.
df1.empty False
Applying Pandas empty method on empty dataframe
Now let us create an empty dataframe with just one column using Pandas DataFrame() function.
# create an empty dataframe df2 = pd.DataFrame({"col1":[]})
When we check the content of the dataframe, we get nothing as it is an empty dataframe.
df2 col1
By apply empty function on this dataframe we should get True as result as it is an empty dataframe.
df2.empty True
Note that a dataframe with missing value is not an empty dataframe. Here is an illustration of applying empty method to a datframe with missing value.
# Create a dataframe with a missing value df3 = pd.DataFrame({"col1":[pd.NA]}) df3 col1 0 <NA>
Correctly, we get False as result if we apply Pandas empty method.
df3.empty False
Our result will change if we drop the NAs and check if it is empty or not.
df3.dropna.empty True
Pandas empty method is often useful sanity check after some series of filtering step in doing data analysis. Here is an example where after filtering out for missing values a dataframe becomes empty.
In this toy example every row has one NA.
df = pd.DataFrame({"col1":[pd.NA,"B",pd.NA], "col2":[1,pd.NA,3]}) df col1 col2 0 <NA> 1 1 B <NA> 2 <NA> 3
And after dropping NAs with dropna() function it becomes empty. And if we check using Pandas empty method, we will correctly get True as answer.
df.dropna().empty True