How do you check if a Pandas DataFrame has zero rows or is empty? | A1Lab@MZeeshanM to PythonEnglish • 2 days ago

How do you check if a Pandas DataFrame has zero rows or is empty?

message-square
0

Check df.empty—which returns True in $O(1)$ time whenever a DataFrame has zero rows (len(df) == 0) OR zero columns (len(df.columns) == 0)—or check len(df) == 0 (equivalently df.shape[0] == 0) when a schema-only DataFrame with defined column headers (pd.DataFrame(columns=["a", "b"])) should count as empty even though its columns exist, while avoiding truth-value testing (if df:) because Pandas raises ValueError: The truth value of a DataFrame is ambiguous.

Basic Example

import pandas as pd

df_completely_empty = pd.DataFrame()
df_schema_only = pd.DataFrame(columns=["id", "score"])
df_populated = pd.DataFrame({"id": [1], "score": [95]})

# 1. Recommended: Use `df.empty` (returns True if rows == 0 OR columns == 0)
print(df_completely_empty.empty)  # Output: True
print(df_schema_only.empty)       # Output: True
print(df_populated.empty)         # Output: False

# 2. Explicit row-count check (returns True specifically when rows == 0):
if len(df_schema_only) == 0:
    print("Zero rows to process.")
# Output: Zero rows to process.

# 3. Guarding a function parameter that could be either `None` or an empty DataFrame:
def process(df: pd.DataFrame | None) -> None:
    if df is None or df.empty:
        return
    print(df.head())

Key Details & Edge Cases

  • df.empty is a boolean property, NOT a method (do not write df.empty()):
    • Calling df.empty() raises TypeError: 'bool' object is not callable. Always access df.empty without parentheses.
  • Never write if not df: or bool(df):
    • Unlike Python lists or dicts, DataFrames do not define implicit truthiness. Writing if df: or if not df: immediately raises ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
  • Edge case where df.empty is True even though len(df) > 0 (0 columns with a non-empty Index):
    • If you slice all columns out of a non-empty DataFrame (df_no_cols = df_populated[[]]), df_no_cols.shape is (1, 0) (len(df_no_cols) == 1, len(df_no_cols.columns) == 0), and df_no_cols.empty returns True because df.empty checks df.size == 0 (rows * cols == 0). Use len(df) == 0 (or df.index.empty) if you specifically need to test whether the row count is zero regardless of columns.
  • DataFrames containing only NaN / None values are NOT considered empty (df.empty == False):
    • pd.DataFrame({"a": [None, None]}).empty returns False because the DataFrame has 2 rows and 1 column (shape == (2, 1)). To check whether a DataFrame is either structurally empty or populated exclusively with missing values, check df.empty or df.isna().all().all().
  • Speed difference (df.empty / len(df) == 0 vs. df.count()):
    • Both df.empty and len(df) == 0 inspect internal index metadata in $O(1)$ constant time without scanning any data cells. Avoid df.count().sum() == 0 for emptiness checks, which scans every column in $O(N \cdot M)$ time and treats all-NaN columns as 0.

Comparison of DataFrame Emptiness Checks in Pandas

Check True When shape == (0, 0)? True When shape == (0, 3) (headers only)? True When shape == (3, 0) (index only, 0 cols)? True When All Cells Are NaN? Best Used When
df.empty (Recommended) Yes Yes Yes No Standard, idiomatic check before running transformations, aggregations, or exports.
len(df) == 0 (or df.shape[0] == 0) Yes Yes No (len(df) is 3) No Checking specifically whether a DataFrame has zero rows regardless of column count.
df is None or df.empty Yes Yes Yes No Validating optional DataFrame arguments or outputs from functions that may return None.
df.empty or df.isna().all().all() Yes Yes Yes Yes Detecting blank spreadsheets/tables that either have no rows or contain only null cells.