How to check whether a pandas DataFrame is empty?

PandasServer Side ProgrammingProgramming

Use the DataFrame.empty property to check if DataFrame contains the data or not (empty or not). The DataFrame.empty attribute returns a boolean value indicating whether this DataFrame is empty or not.

If the DataFrame is empty, it will return True. and it will return False If the DataFrame is not empty.

Example 1

In the following example, we have initialized a DataFrame with some data and then applied the empty attribute to check if the empty attribute returns False or not.

# importing pandas package
import pandas as pd

# create an empty DataFrame
df = pd.DataFrame([['a','b','c'],['b','c','d'],
['d','e','f'],['f','g','h']],
columns=['Col1','Col2','Col3'])

print("DataFrame:")
print(df)

# Apply empty attribute to the DataFrame
print('Output:')
print(df.empty)

Output

The output is given below −

DataFrame:
 Col1 Col2 Col3
0   a   b   c
1   b   c   d
2   d   e   f
3   f   g   h

Output:
False

The attribute empty successfully returns the boolean value “False” as output for the given DataFrame.

Example 2

For this example, we will apply the empty attribute to the empty DataFrame, so that initially we have created an empty DataFrame using pandas DataFrame constructor.

# importing pandas package
import pandas as pd

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

print("DataFrame:")
print(df)

# Apply empty attribute to the DataFrame
print('Output:')
print(df.empty)

Output

The output is given below −

DataFrame:
Empty DataFrame
Columns: []
Index: []

Output:
True

The empty attribute generated the output for True the given DataFrame, it is a valid output Since the given dataframe is empty.

raja
Updated on 08-Mar-2022 12:04:22

Advertisements