Selecting a pandas column raises KeyError although the column seems to exist
Fix it fast
Most common cause, 1 of 3The header has extra spaces or different capital letters
Clean the labels once, right after loading, using the string methods that work on df.columns.
df.columns = df.columns.str.strip().str.lower().str.replace(" ", "_")
df["price"]Short answer
A KeyError whose traceback shows the line 'If we have a listlike key, _check_indexing_error will raise' means pandas has no column with exactly that label. Usually the header carries spaces or other casing, read_csv split the file wrongly, or the column became the index. Print repr() of every column name to see which. Applies to pandas 3.1.
Which cause do you have?
Print the exact column labels, quotes included, plus the index name. Hidden spaces, one giant joined label or the name sitting on the index each point to a different cause.
print([repr(c) for c in df.columns])
print("index:", df.index.name, df.index.names)Then find the line you see in this list and open its fix:
- 1The header has extra spaces or different capital letters
repr shows ' Price' or 'price ' or 'PRICE' while the code asks for 'Price' - 2read_csv used the wrong separator or the wrong header row
The repr list holds one long label such as 'date;price;qty', or names like 'Unnamed: 0', or values from the first data row - 3The column became the index
The first-step output prints the missing name as the index name, after set_index, groupby or read_csv(index_col=...)
What does the error look like?
KeyError: 'Price'# If we have a listlike key, _check_indexing_error will raiseraise KeyError(key) from errKeyError: "['qty'] not in index"
Cause 1 of 3
The header has extra spaces or different capital letters
You seerepr shows ' Price' or 'price ' or 'PRICE' while the code asks for 'Price'
Check
Column lookup in pandas is exact: the indexing guide says every label you ask for must be present, or KeyError is raised. A spreadsheet export that writes ' Price' or 'price' is a different label from 'Price', even though it looks the same when printed as a table.
print([c for c in df.columns if c.strip().lower() == "price"])Fix
Clean the labels once, right after loading, using the string methods that work on df.columns. Then use the cleaned names everywhere in your code.
df.columns = df.columns.str.strip().str.lower().str.replace(" ", "_")
df["price"]Verify
The repr list now shows plain names such as 'price', and the selection returns a Series.
print(df["price"].head())Confirmed by pandas.pydata.org
Cause 2 of 3
read_csv used the wrong separator or the wrong header row
You seeThe repr list holds one long label such as 'date;price;qty', or names like 'Unnamed: 0', or values from the first data row
Check
When a file separated by semicolons or tabs is read with the default comma, every row lands in a single column whose name is the whole header line. A title line above the real header has a similar effect: pandas takes that line as the header, so none of your names exist.
with open("data.csv") as f:
print([next(f) for _ in range(3)])Fix
Pass the real separator, and point header (or skiprows) at the line that holds the column names.
df = pd.read_csv("data.csv", sep=";")
# column names sit on the third non-blank line (header counts from 0)
df = pd.read_csv("data.csv", sep=";", header=2)Verify
df.columns now lists each field separately and df.shape shows more than one column.
print(df.shape, df.columns.tolist())Confirmed by pandas.pydata.org
Cause 3 of 3
The column became the index
You seeThe first-step output prints the missing name as the index name, after set_index, groupby or read_csv(index_col=...)
Check
Once a column is moved into the index, df['name'] no longer finds it, because square brackets search only the columns. groupby results and files read with index_col are the usual places this happens without an explicit set_index call.
print(df.index.name)Fix
Turn the index back into a column with reset_index, or read the values from df.index if you meant to keep it there.
df = df.reset_index()
df["date"]
# or keep the index and read it directly
df.indexVerify
The name appears in df.columns and the selection works.
print("date" in df.columns)Confirmed by pandas.pydata.org
How do I stop it coming back?
- Normalise column names inside the one function that loads each file, so every script sees the same labels.
- Right after loading, compare the expected names with set(df.columns) and stop with the missing ones listed, so a renamed header fails early and clearly.
- Write sep= explicitly for every file format you accept instead of relying on the comma default.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine on the same stack: stegnor.com, Menulo, ShopGo.