{"record":{"id":"162784ad0679f674","repo":"pandas-dev/pandas","slug":"length-of-values-len-data-does-not-match-leng","errorCode":null,"errorMessage":"Length of values ({len(data)}) does not match length of index ({len(index)})","messagePattern":"Length of values \\((.+?)\\) does not match length of index \\((.+?)\\)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/common.py","lineNumber":611,"sourceCode":"    ------\n    object : obj with modified attribute.\n    \"\"\"\n    if condition:\n        old_value = getattr(obj, attr)\n        setattr(obj, attr, value)\n    try:\n        yield obj\n    finally:\n        if condition:\n            setattr(obj, attr, old_value)\n\n\ndef require_length_match(data: Any, index: Index) -> None:\n    \"\"\"\n    Check the length of data matches the length of the index.\n    \"\"\"\n    if len(data) != len(index):\n        raise ValueError(\n            \"Length of values \"\n            f\"({len(data)}) \"\n            \"does not match length of index \"\n            f\"({len(index)})\"\n        )\n\n\n_cython_table = {\n    builtins.sum: \"sum\",\n    builtins.max: \"max\",\n    builtins.min: \"min\",\n    np.all: \"all\",\n    np.any: \"any\",\n    np.sum: \"sum\",\n    np.nansum: \"sum\",\n    np.mean: \"mean\",\n    np.nanmean: \"mean\",\n    np.prod: \"prod\",","sourceCodeStart":593,"sourceCodeEnd":629,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/common.py#L593-L629","documentation":"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.","triggerScenarios":"`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.","commonSituations":"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.","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)`."],"exampleFix":"# before\ndf['agg'] = df.groupby('k')['v'].mean()   # length = #groups != len(df)\n\n# after\ndf['agg'] = df['k'].map(df.groupby('k')['v'].mean())","handlingStrategy":"validation","validationCode":"def assert_length_match(values, index):\n    if len(values) != len(index):\n        raise ValueError(f'len(values)={len(values)} != len(index)={len(index)}')\n\ndf['new'] = values  # only after assert_length_match(values, df.index)","typeGuard":"def lengths_match(values, index) -> bool:\n    return len(values) == len(index)","tryCatchPattern":"try:\n    df['new'] = values\nexcept ValueError as e:\n    if 'Length of values' in str(e):\n        if len(values) < len(df):\n            values = df['key'].map(dict(zip(df['key'].unique(), values)))\n        df['new'] = values\n    else:\n        raise","preventionTips":["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."],"tags":["length-mismatch","assignment","index-alignment","valueerror"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}