pandas-dev/pandas · error · ValueError
Length of values ({len(data)}) does not match length of inde
Error message
Length of values ({len(data)}) does not match length of index ({len(index)}) What it means
Raised by require_length_match (pandas/core/common.py:611), invoked when assigning an array-like of values to a Series/DataFrame whose index has a different length. pandas requires the values to align 1:1 with the index unless an explicit index is provided, so a length mismatch is a hard error rather than silent broadcasting.
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 71959b8cb9)
Solutions
- Make the values length match the index: slice or pad to `len(df)` / `len(index)`.
- If assigning per-group results, map them back with map/merge rather than positional assignment: `df['g'] = df['key'].map(group_result)`.
- Provide an explicit index that matches: `pd.Series(values, index=matching_index)` before assignment.
- Use transform to broadcast group results to the original length: `df.groupby('k')['v'].transform(func)`.
Example fix
# before
df['agg'] = df.groupby('k')['v'].mean() # length = #groups != len(df)
# after
df['agg'] = df['k'].map(df.groupby('k')['v'].mean()) Defensive patterns
Strategy: validation
Validate before calling
def assert_length_match(values, index):
if len(values) != len(index):
raise ValueError(f'len(values)={len(values)} != len(index)={len(index)}')
df['new'] = values # only after assert_length_match(values, df.index) Type guard
def lengths_match(values, index) -> bool:
return len(values) == len(index) Try / catch
try:
df['new'] = values
except ValueError as e:
if 'Length of values' in str(e):
if len(values) < len(df):
values = df['key'].map(dict(zip(df['key'].unique(), values)))
df['new'] = values
else:
raise Prevention
- Use df['key'].map(...) or merge to assign per-group results to the full index.
- Use groupby.transform to broadcast reductions to the original length.
- Check len(values) == len(df) before positional assignment.
When it happens
Trigger: `df['new'] = [1,2,3]` on a 4-row frame; `pd.Series([1,2,3], index=[0,1,2,3])`; `df.assign(col=np.zeros(5))` on a 3-row frame; setting a column from a groupby/aggregate whose length differs from the original index.
Common situations: Assigning a list/ndarray computed from a subset or aggregation back to the full frame without reindexing; off-by-one in generated lists; applying a per-group result to the parent index.
Related errors
- Lengths must match
- Lengths must match.
- new categories need to have the same number of items as the
- Value must be an instance of {type_repr}
- Value must be one of {pp_values}
AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07).
Data as JSON: /api/errors/162784ad0679f674.
Report an issue: GitHub.