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.emptyis a boolean property, NOT a method (do not writedf.empty()):- Calling
df.empty()raisesTypeError: 'bool' object is not callable. Always accessdf.emptywithout parentheses.
- Calling
- Never write
if not df:orbool(df):- Unlike Python lists or dicts, DataFrames do not define implicit truthiness. Writing
if df:orif not df:immediately raisesValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
- Unlike Python lists or dicts, DataFrames do not define implicit truthiness. Writing
- Edge case where
df.emptyisTrueeven thoughlen(df) > 0(0columns with a non-empty Index):- If you slice all columns out of a non-empty DataFrame (
df_no_cols = df_populated[[]]),df_no_cols.shapeis(1, 0)(len(df_no_cols) == 1,len(df_no_cols.columns) == 0), anddf_no_cols.emptyreturnsTruebecausedf.emptychecksdf.size == 0(rows * cols == 0). Uselen(df) == 0(ordf.index.empty) if you specifically need to test whether the row count is zero regardless of columns.
- If you slice all columns out of a non-empty DataFrame (
- DataFrames containing only
NaN/Nonevalues are NOT considered empty (df.empty == False):pd.DataFrame({"a": [None, None]}).emptyreturnsFalsebecause 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, checkdf.empty or df.isna().all().all().
- Speed difference (
df.empty/len(df) == 0vs.df.count()):- Both
df.emptyandlen(df) == 0inspect internal index metadata in $O(1)$ constant time without scanning any data cells. Avoiddf.count().sum() == 0for emptiness checks, which scans every column in $O(N \cdot M)$ time and treats all-NaNcolumns as0.
- Both
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. |
You must log in or register to comment.
