Following are the several ways to check whether the dataframe is empty or not.

Using empty()

To check if the pandas dataframe is empty or not we can use the <strong>empty()</strong> method. This method returns a boolean value which indicates whether the dataframe is empty or not.

See the following example:

import pandas as pd

# create an empty pandas dataframe
df = pd.DataFrame()

# check if the dataframe is empty
print(df.empty)

Output

True

In the above example, we created an empty pandas data frame using the DataFrame() constructor. We then used the empty attribute to check if the data frame is empty or not based on the boolean value. If the value is true, then data frame is empty else it is not.

Using size()

Using the size attribute we can also check if the dataframe is empty or not. The size() attribute returns the number of elements in the data frame. If the value returned by the size() is 0, then it means the dataframe is empty.

import pandas as pd

# create an empty pandas dataframe
df = pd.DataFrame()

# check if the dataframe is empty
print(df.size == 0)

Output

True

In the above example, we created an empty pandas data frame using the DataFrame() constructor. We then used the size attribute to check if the data frame is empty, which returned True.

If a pandas data frame is empty, we can handle it in different ways, depending on the use case. For example, we can fill the data frame with default values, delete the data frame, or skip the operation that we want to perform.

Categorized in:

Tagged in: