// Python
KeyError on a pandas column: why it happens and how to fix it
Every example on this page was run on 2 December 2026 in Python 3.14, and the output under each one is what it printed. How we test these posts.
A pandas KeyError on a column, such as KeyError: 'price', means the label inside df['price'] is not one of the DataFrame’s column names. pandas compares names exactly, so a stray space, a different capital letter or a column that moved into the index all count as missing. The most common fix is to print df.columns.tolist(), see the real names, and clean them with df.columns.str.strip().
What does KeyError mean for a pandas column?
KeyError for a pandas column means df['name'] looked for a column label called exactly name and found none. The last line of the traceback is the label pandas looked for, in quotes. Here the CSV header has a space after the comma, so the column is called ' price', not 'price':
import io
import pandas as pd
csv = "item, price\npen, 10\nbook, 250\n"
df = pd.read_csv(io.StringIO(csv))
print(df["price"].sum())
import io
import pandas as pd
csv = "item, price\npen, 10\nbook, 250\n"
df = pd.read_csv(io.StringIO(csv))
print(df["price"].sum())Output
Traceback (most recent call last):
File "/lib/python3.14/site-packages/pandas/core/indexes/base.py", line 3641, in get_loc
return self._engine.get_loc(casted_key)
~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^
File "pandas/_libs/index.pyx", line 168, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/index.pyx", line 197, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 7668, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 7676, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'price'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "main.py", line 6, in <module>
print(df["price"].sum())
~~^^^^^^^^^
File "/lib/python3.14/site-packages/pandas/core/frame.py", line 4378, in __getitem__
indexer = self.columns.get_loc(key)
File "/lib/python3.14/site-packages/pandas/core/indexes/base.py", line 3648, in get_loc
raise KeyError(key) from err
KeyError: 'price'The table prints fine with print(df), because a leading space is invisible in the header. The traceback comes in two parts, and most of it is pandas’ own code. Read the frame that names main.py for the line that failed, and the last line for the label pandas could not find.
Why does pandas say KeyError when the column exists?
pandas says KeyError for a column you can see because the name you typed and the name in df.columns differ in a way the printed table hides. The usual causes, most common first:
- Spaces around the name, from a CSV header written as
a, bor a spreadsheet cell with a trailing space. - Different case:
Pricein the file,pricein the code. - The column is in the index, after
set_index,groupbyorread_csv(index_col=...). - The file was read with the wrong separator, so the whole header became one column called
item;price.
repr shows every one of these at once, because it puts quotes around each name:
import io
import pandas as pd
csv = "Item , Price\npen, 10\nbook, 250\n"
df = pd.read_csv(io.StringIO(csv))
print(df.columns.tolist())
print("price" in df.columns)
import io
import pandas as pd
csv = "Item , Price\npen, 10\nbook, 250\n"
df = pd.read_csv(io.StringIO(csv))
print(df.columns.tolist())
print("price" in df.columns)Output
['Item ', ' Price'] False
How do I fix KeyError for a pandas column?
Fix a pandas column KeyError by making the names in df.columns match the names your code uses, once, straight after loading the data. Then every later df['price'] works.
Strip spaces and lower the case of every column name
Clean the names once: df.columns = df.columns.str.strip().str.lower(). This removes leading and trailing spaces and makes the case predictable:
import io
import pandas as pd
csv = "Item , Price\npen, 10\nbook, 250\n"
df = pd.read_csv(io.StringIO(csv))
df.columns = df.columns.str.strip().str.lower()
print(df.columns.tolist())
print(df["price"].sum())
import io
import pandas as pd
csv = "Item , Price\npen, 10\nbook, 250\n"
df = pd.read_csv(io.StringIO(csv))
df.columns = df.columns.str.strip().str.lower()
print(df.columns.tolist())
print(df["price"].sum())Output
['item', 'price'] 260
When the spaces come from a CSV header, pd.read_csv(..., skipinitialspace=True) drops the space after each separator while reading, in the header and in the values. It does not remove a space before the separator, so str.strip() is the safer fix. The read_csv reference lists both options.
Read the file with the right separator
A semicolon file read with the default comma separator gives one column whose name is the whole header line. Pass sep=";":
import io
import pandas as pd
csv = "item;price\npen;10\nbook;250\n"
wrong = pd.read_csv(io.StringIO(csv))
print(wrong.columns.tolist())
right = pd.read_csv(io.StringIO(csv), sep=";")
print(right["price"].sum())
import io
import pandas as pd
csv = "item;price\npen;10\nbook;250\n"
wrong = pd.read_csv(io.StringIO(csv))
print(wrong.columns.tolist())
right = pd.read_csv(io.StringIO(csv), sep=";")
print(right["price"].sum())Output
['item;price'] 260
Why do I get a KeyError after groupby or set_index?
A KeyError after groupby or set_index happens because both move the key column out of df.columns and into the index. The column still shows in print(df), on the left, but df['city'] no longer finds it:
import pandas as pd
df = pd.DataFrame({"city": ["Pune", "Pune", "Delhi"], "sales": [5, 7, 4]})
totals = df.groupby("city").sum()
print(totals.index.name)
print(totals.columns.tolist())
try:
totals["city"]
except KeyError as e:
print("KeyError:", e)
import pandas as pd
df = pd.DataFrame({"city": ["Pune", "Pune", "Delhi"], "sales": [5, 7, 4]})
totals = df.groupby("city").sum()
print(totals.index.name)
print(totals.columns.tolist())
try:
totals["city"]
except KeyError as e:
print("KeyError:", e)Output
city ['sales'] KeyError: 'city'
Bring the column back with reset_index(), or pass as_index=False to groupby:
import pandas as pd
df = pd.DataFrame({"city": ["Pune", "Pune", "Delhi"], "sales": [5, 7, 4]})
totals = df.groupby("city", as_index=False).sum()
print(totals["city"].tolist())
indexed = df.set_index("city").reset_index()
print(indexed.columns.tolist())
import pandas as pd
df = pd.DataFrame({"city": ["Pune", "Pune", "Delhi"], "sales": [5, 7, 4]})
totals = df.groupby("city", as_index=False).sum()
print(totals["city"].tolist())
indexed = df.set_index("city").reset_index()
print(indexed.columns.tolist())Output
['Delhi', 'Pune'] ['city', 'sales']
While the label is in the index, read it with totals.index or totals.loc['Pune'] instead.
What does KeyError “not in index” mean in pandas?
KeyError: "['tax'] not in index" means you selected several columns with a list, as in df[['price', 'tax']], and the labels in the message are the ones that are missing. When none of the labels exist, pandas words it as None of [Index([...])] are in the [columns]:
import pandas as pd
df = pd.DataFrame({"item": ["pen", "book"], "price": [10, 250]})
for cols in (["price", "tax"], ["tax", "fee"]):
try:
df[cols]
except KeyError as e:
print(e)
import pandas as pd
df = pd.DataFrame({"item": ["pen", "book"], "price": [10, 250]})
for cols in (["price", "tax"], ["tax", "fee"]):
try:
df[cols]
except KeyError as e:
print(e)Output
"['tax'] not in index" "None of [Index(['tax', 'fee'], dtype='str')] are in the [columns]"
The fixes are the same as for one column: check the names, clean them, or select only what is there with df[[c for c in cols if c in df.columns]].
How do I get a pandas column without a KeyError?
Get a column that may be missing without a KeyError by testing for it with in df.columns, or with df.get('name'), which returns None (or a default you pass) instead of raising:
import pandas as pd
df = pd.DataFrame({"item": ["pen", "book"], "price": [10, 250]})
print(df.get("discount"))
print(df.get("discount", pd.Series([0, 0])).tolist())
if "price" in df.columns:
print(df["price"].max())
import pandas as pd
df = pd.DataFrame({"item": ["pen", "book"], "price": [10, 250]})
print(df.get("discount"))
print(df.get("discount", pd.Series([0, 0])).tolist())
if "price" in df.columns:
print(df["price"].max())Output
None [0, 0] 250
Use this only when a missing column is normal, such as an optional field in an export. When the column must be there, let the KeyError stop the program, so the bad file is noticed. The DataFrame.get reference covers the default.
How do I catch this early in my own code?
Catch a column KeyError early by checking the columns right after loading, in one place, with a clear message:
import io
import pandas as pd
csv = "item,cost\npen,10\n"
df = pd.read_csv(io.StringIO(csv))
needed = {"item", "price"}
missing = needed - set(df.columns)
if missing:
print("missing columns:", sorted(missing), "found:", df.columns.tolist())
import io
import pandas as pd
csv = "item,cost\npen,10\n"
df = pd.read_csv(io.StringIO(csv))
needed = {"item", "price"}
missing = needed - set(df.columns)
if missing:
print("missing columns:", sorted(missing), "found:", df.columns.tolist())Output
missing columns: ['price'] found: ['item', 'cost']
A check like this turns a long traceback deep in your analysis into one line that names the file’s real columns. Python’s own KeyError documentation explains the exception every dict and DataFrame lookup raises.
Related errors
AttributeError: 'DataFrame' object has no attribute 'price' is the same mistake written as df.price, and the same cleaning fixes it. KeyError: 0 comes from df[0] on a DataFrame whose columns have names: use df.iloc[0] for the first row. A None that reaches square brackets is TypeError: ‘NoneType’ object is not subscriptable, which also covers pandas’ inplace=True.