There are many use cases where you have to check whether the Panda DataFrame is filled with data or empty. Empty DataFrame has no rows.
To check if the pandas DataFrame is empty or not, use the DataFrame attribute empty
. Here is an example.
import pandas as pd #create empty DataFrame df = pd.DataFrame() #check if the DataFrame is empty if df.empty: print("DataFrame is empty.") else: print("DataFrame is not empty.")
Output:
DataFrame is empty.
One such use case is writing unit test cases.
Suppose you have an API that returns a response DataFrame. You can write a test case to check whether you are getting a DataFrame filled with data or an empty DataFrame. For this use Python assert statement.
assert df.empty
It raises an assertion when the Dataframe is Empty.
More programmatically you can use the following syntax.
self.assertTrue(df.empty, "Dataframe is empty.")
Using an empty
attribute to detect if the Pandas DataFrame is empty or not is the most effective technique.