pandas-dev/pandas · error · ValueError

Index length mismatch

Error message

Index length mismatch: {len(index)} vs. {N}

What it means

Raised by SparseFrameAccessor._prep_index when len(index) does not equal N, the first dimension of the source sparse matrix. The row labels must exactly match the matrix's row count.

Solutions

  1. Pass index=None to let pandas assign a default RangeIndex.
  2. Construct index from shape: index=pd.RangeIndex(mat.shape[0]).
  3. Slice/align the index to the matrix before calling: index = index[:mat.shape[0]].

Example fix

# before
pd.DataFrame.sparse.from_spmatrix(mat, index=old_index)  # len mismatch
# after
idx = pd.RangeIndex(mat.shape[0])
pd.DataFrame.sparse.from_spmatrix(mat, index=idx)
Defensive patterns

Strategy: validation

Validate before calling

def index_matches_matrix(index, mat) -> bool:
    return index is None or len(index) == mat.shape[0]

Type guard

def valid_index_for(index, mat) -> bool:
    return index is None or len(list(index)) == mat.shape[0]

Try / catch

try:
    df = pd.DataFrame.sparse.from_spmatrix(mat, index=index)
except ValueError as e:
    if 'Index length mismatch' in str(e):
        df = pd.DataFrame.sparse.from_spmatrix(mat)
    else:
        raise

Prevention

When it happens

Trigger: pd.DataFrame.sparse.from_spmatrix(mat, index=some_series) where len(some_series) != mat.shape[0]; passing a DatetimeIndex of the wrong length.

Common situations: Index built from a different sample; matrix transposed but index not flipped; reusing labels from a previous run after slicing the matrix.

Related errors


AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11). Data as JSON: /api/errors/6a012d9d94268476. Report an issue: GitHub.

Appendix: source

Thrown at pandas/core/arrays/sparse/accessor.py:504

        from pandas.core.indexes.api import (
            default_index,
            ensure_index,
        )

        N, K = data.shape
        if index is None:
            index = default_index(N)
        else:
            index = ensure_index(index)
        if columns is None:
            columns = default_index(K)
        else:
            columns = ensure_index(columns)

        if len(columns) != K:
            raise ValueError(f"Column length mismatch: {len(columns)} vs. {K}")
        if len(index) != N:
            raise ValueError(f"Index length mismatch: {len(index)} vs. {N}")
        return index, columns

View on GitHub (pinned to 3b7651241d)