Home › Python

ValueError: Length of values does not match length of index (Python) — how to fix

ValueError: Length of values (3) does not match length of index (5)

Quick fix: Make the values exactly len(df) long. Check with print(len(values), len(df)). If you are adding a column from another Series, align on the index instead (df['new'] = other_series or df.merge(...)); if the values came from a filtered/grouped result, use .loc on the same rows or groupby(...).transform(...).

What it means

When you write df["col"] = something and something is a plain list, tuple or NumPy array, pandas puts the values in row order. That only works if there is exactly one value per row. The numbers in the message tell you both sides: Length of values (3) is what you passed, length of index (5) is how many rows the DataFrame has.

import pandas as pd

df = pd.DataFrame({"a": [1, 2, 3, 4, 5]})
df["b"] = [10, 20, 30]        # ValueError: Length of values (3) does not match length of index (5)

A pandas Series behaves differently: it is aligned by index label, and missing labels become NaN, so it does not raise this error.

Cause 1: the list was built from a different number of rows

Typical case: a loop or list comprehension that skips some rows, or a result built from a filtered DataFrame.

values = [x * 2 for x in df["a"] if x > 2]   # only 3 items
df["b"] = values                              # error

Fix: produce one value per row, e.g. with a vectorised expression or where:

df["b"] = (df["a"] * 2).where(df["a"] > 2)   # NaN where the condition is false

Or assign only to the matching rows:

mask = df["a"] > 2
df.loc[mask, "b"] = df.loc[mask, "a"] * 2

Cause 2: assigning an aggregated groupby result

groupby().sum() returns one row per group, not per row:

df["total"] = df.groupby("team")["score"].sum().values   # wrong length

Use transform, which returns a result with the original length and index:

df["total"] = df.groupby("team")["score"].transform("sum")

Cause 3: .values / .tolist() threw away the index

If you convert a Series from another DataFrame to an array, pandas can no longer align it, so lengths must match exactly. Keep it as a Series (aligned on index) or merge on a key column:

df = df.merge(other[["id", "price"]], on="id", how="left")

Cause 4: setting the index or columns

The same error appears when you replace the whole index with the wrong number of labels:

df.index = ["x", "y"]      # df has 5 rows -> ValueError

Check len(df) first, and use df.set_index("col") if you want to use an existing column as the index.

Debugging tip

Print both lengths right before the failing line:

print(len(values), len(df))

If the DataFrame is shorter than you expect, an earlier dropna(), drop_duplicates() or filter removed rows. If you work on a filtered copy, call .reset_index(drop=True) only when you intend to discard the original labels.

Last updated 2026-12-02.