pandas-dev/pandas · error · AssertionError

length mismatch: {len(self)} vs. {len(other)}

Error message

length mismatch: {len(self)} vs. {len(other)}

What it means

Raised (as AssertionError) by SparseArray._arith_method when a non-scalar, non-SparseArray operand is converted to ndarray and its length differs from len(self). Sparse arithmetic requires element-wise alignment; mismatched lengths can't be broadcast and the operation is rejected before the sparse kernel is invoked.

Source

Thrown at pandas/core/arrays/sparse/array.py:1970

            return _wrap_result(op_name, result, self.sp_index, fill)

        else:
            if not isinstance(
                other, (list, np.ndarray, ExtensionArray)
            ) and not ops.has_castable_attr(other):
                warnings.warn(
                    f"Operation with {type(other).__name__} is deprecated. "
                    "In a future version these will be treated as scalar-like. "
                    "To retain the old behavior, explicitly wrap in a Series "
                    "instead.",
                    Pandas4Warning,
                    stacklevel=find_stack_level(),
                )

            other = np.asarray(other)
            with np.errstate(all="ignore"):
                if len(self) != len(other):
                    raise AssertionError(
                        f"length mismatch: {len(self)} vs. {len(other)}"
                    )
                if not isinstance(other, SparseArray):
                    dtype = getattr(other, "dtype", None)
                    other = SparseArray(other, fill_value=self.fill_value, dtype=dtype)
                return _sparse_array_op(self, other, op, op_name)

    def _cmp_method(self, other, op) -> SparseArray:
        if (
            is_list_like(other)
            and not isinstance(other, (list, np.ndarray, ExtensionArray))
            and not ops.has_castable_attr(other)
        ):
            warnings.warn(
                f"Operation with {type(other).__name__} is deprecated. "
                "In a future version these will be treated as scalar-like. "
                "To retain the old behavior, explicitly wrap in a Series "
                "instead.",

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Align lengths explicitly: other = np.asarray(other); assert len(other) == len(sparse_arr).
  2. Use Series arithmetic which aligns on index instead of position: pd.Series(sparse_arr) + pd.Series(other).
  3. If the operand is meant to be scalar, pass a scalar (int/float) instead of a 1-element list.

Example fix

// before
out = sparse_arr + np.array([1, 2])  # raises if len(sparse_arr) != 2

// after
out = pd.Series(sparse_arr) + pd.Series(np.array([1, 2]), index=...)  # index-aligned
Defensive patterns

Strategy: validation

Validate before calling

import numpy as np

def arith_sparse_safe(arr, other):
    other_arr = np.asarray(other)
    if other_arr.ndim == 1 and len(other_arr) != len(arr):
        raise ValueError(f'length {len(other_arr)} != {len(arr)}')
    return arr + other_arr

Type guard

import numpy as np

def lengths_match(arr, other) -> bool:
    o = np.asarray(other)
    return o.ndim == 0 or len(o) == len(arr)

Try / catch

try:
    out = sparse_arr + other
except AssertionError as e:
    if 'length mismatch' in str(e):
        # align via Series instead
        out = (pd.Series(sparse_arr) + pd.Series(other)).array
    else:
        raise

Prevention

When it happens

Trigger: sparse_arr + np.array([1,2,3]) of different length, sparse_arr * list_of_wrong_length, or arithmetic between two Series whose indexes were silently reindexed to different lengths.

Common situations: Broadcasting mistakes (assuming a column vector aligns with a row), stale cached lengths, or operating on filtered sublists without re-aligning indexes.

Related errors


AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07). Data as JSON: /api/errors/7a333fc7190fc73f. Report an issue: GitHub.