pandas-dev/pandas · error · ValueError

Length of values ( ) does not match length of index ( )

Error message

Length of values ({len(data)}) does not match length of index ({len(index)})

What it means

Raised by require_length_match when data passed to construct/assign into a Series/Index does not match the supplied Index length. pandas refuses to broadcast arbitrary-length data onto an index because silent truncation or padding would hide logic errors. The message reports both lengths so the mismatch is obvious.

Solutions

  1. Verify len(data) == len(index) before assignment.
  2. Use an alignable Series instead of a list so pandas can reindex.
  3. Broadcast a scalar explicitly: df['new'] = scalar.
  4. Reset the index or reindex both sides to a common index before assigning.

Example fix

// before
df['ratio'] = (df['a'] / df['a'].sum()).tolist()[1:]  # off by one
// after
ratios = df['a'] / df['a'].sum()
assert len(ratios) == len(df)
df['ratio'] = ratios
Defensive patterns

Strategy: validation

Validate before calling

if len(data) != len(index):
    raise ValueError(f'len(data)={len(data)} != len(index)={len(index)}')
s = pd.Series(data, index=index)

Prevention

When it happens

Trigger: pd.Series([1,2,3], index=[10,20,30,40]); df['new'] = [1,2] on a 3-row frame; assign with a list whose len != len(df); construction with mismatched numpy arrays.

Common situations: Hardcoded lists that drift from data length; aggregations that change cardinality then get assigned back; off-by-one in slicing that produces N-1 values; groupby transforms that did not broadcast.

Related errors


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

Appendix: source

Thrown at pandas/core/common.py:611

    ------
    object : obj with modified attribute.
    """
    if condition:
        old_value = getattr(obj, attr)
        setattr(obj, attr, value)
    try:
        yield obj
    finally:
        if condition:
            setattr(obj, attr, old_value)


def require_length_match(data: Any, index: Index) -> None:
    """
    Check the length of data matches the length of the index.
    """
    if len(data) != len(index):
        raise ValueError(
            "Length of values "
            f"({len(data)}) "
            "does not match length of index "
            f"({len(index)})"
        )


_cython_table = {
    builtins.sum: "sum",
    builtins.max: "max",
    builtins.min: "min",
    np.all: "all",
    np.any: "any",
    np.sum: "sum",
    np.nansum: "sum",
    np.mean: "mean",
    np.nanmean: "mean",
    np.prod: "prod",

View on GitHub (pinned to 3b7651241d)