ValueError: Length of values does not match length of index
1 · The lesson
readWhat this error means
You tried to put a list (or an array) into a pandas DataFrame column, and the list has a different number of items than the DataFrame has rows. The numbers in brackets tell you both sizes: Length of values (3) is your list, length of index (4) is the number of rows. pandas refuses to guess which row each value belongs to, so it stops.
When you see it
Traceback (most recent call last): File "main.py", line 4, in <module> df["score"] = [91, 78, 55] ~~^^^^^^^^^ ... ValueError: Length of values (3) does not match length of index (4)
The traceback continues inside pandas for several lines. Your own line is the first one, near the top.
Why it happens
1. The list was built from different data. You made a list in a loop over one thing, then put it into a DataFrame made from something else.
import pandas as pd df = pd.DataFrame({"name": ["Ada", "Grace", "Linus", "Hedy"]}) df["score"] = [91, 78, 55] # ValueError: 3 values, 4 rows
2. You filtered the DataFrame, or dropped rows, after making the list. dropna(), drop_duplicates() or a filter like df[df["age"] > 18] changes the number of rows. A list you made earlier still has the old length.
3. The loop skipped some rows. A for loop with an if inside, or a continue, only appends for some rows. The list ends up shorter than the DataFrame.
import pandas as pd df = pd.DataFrame({"name": ["Ada", "Grace", "Linus"], "score": [91, None, 55]}) grades = [] for s in df["score"]: if pd.notna(s): grades.append("pass" if s > 60 else "fail") print(len(grades), len(df)) # 2 3: one row was skipped
How to fix it
Compare the two lengths first. Print len(your_list) and len(df) just before the assignment. Then decide which one is wrong.
Build the new column from the DataFrame's own rows, so the length can't be different. Most new columns can be written as a calculation on other columns:
import pandas as pd df = pd.DataFrame({"name": ["Ada", "Grace", "Linus"], "score": [91, None, 55]}) df["passed"] = df["score"] > 60 df["grade"] = df["score"].apply(lambda s: "missing" if pd.isna(s) else ("pass" if s > 60 else "fail")) print(df["grade"].tolist()) # ['pass', 'missing', 'fail']
In a loop, add a value for every row, including the ones you would skip. Use None for the rows that have no value:
import pandas as pd df = pd.DataFrame({"name": ["Ada", "Grace", "Linus"], "score": [91, None, 55]}) grades = [] for s in df["score"]: grades.append(None if pd.isna(s) else ("pass" if s > 60 else "fail")) df["grade"] = grades print(df["grade"].tolist()) # ['pass', None, 'fail']
When the values belong to specific rows, match them by a key, not by position. Put them in a dict and use .map(). Rows with no match get NaN instead of causing an error:
import pandas as pd df = pd.DataFrame({"name": ["Ada", "Grace", "Linus", "Hedy"]}) scores = {"Ada": 91, "Grace": 78, "Linus": 55} df["score"] = df["name"].map(scores) print(df["score"].tolist()) # [91.0, 78.0, 55.0, nan]
For two whole tables, df.merge(other, on="name", how="left") does the same thing.
When you'd see this in real code
- Scraping a web page into one list per field, where some items have no price. The
priceslist is shorter than thetitleslist. - Calling an API once per row and appending only the successful answers.
- Predictions from a machine learning model made on
X_testand assigned to the full DataFrame instead of the test rows. - Running
df = df.dropna()in a notebook cell after the list was already built in an earlier cell.
Renaming columns with a list of the wrong size gives a similar error with different wording: ValueError: Length mismatch: Expected axis has 1 elements, new values have 2 elements. The fix is the same: make the two lengths match.
Related errors
- SettingWithCopyWarning: the warning when you add a column to a filtered part of a DataFrame.
- ValueError: The truth value of a Series is ambiguous: another pandas ValueError, from using
iforandwith a column. - ValueError: not enough values to unpack: the same kind of count mismatch in plain Python.
- KeyError: the column name you used doesn't exist.
See Also
- All Python errors: the full index, by type and by when it happens.
- pandas (tutorial)
- pandas cheat sheet
- Data science with pandas
Found this useful? Share it with a friend who’s learning Python.