Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4791 pages
Databases and Redis

Selecting a pandas column raises KeyError although the column seems to exist

Your error

KeyError: 'Price'3 more lines it can show

Fix it fast

Most common cause, 1 of 3

The header has extra spaces or different capital letters

Clean the labels once, right after loading, using the string methods that work on df.columns.

Fix
df.columns = df.columns.str.strip().str.lower().str.replace(" ", "_")
df["price"]
Did this fix it?
Full steps for this cause: check, fix, verify

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.

  • Applies to pandas 3.1.1, Python 3.11 or later
  • Updated
  • By Maaz Zindani, Senior Software Engineer

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.

Run this first
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:

  1. 1The header has extra spaces or different capital lettersrepr shows ' Price' or 'price ' or 'PRICE' while the code asks for 'Price'
  2. 2read_csv used the wrong separator or the wrong header rowThe repr list holds one long label such as 'date;price;qty', or names like 'Unnamed: 0', or values from the first data row
  3. 3The column became the indexThe 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 raise
  • raise KeyError(key) from err
  • KeyError: "['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.

Check
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.

Fix
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.

Verify
print(df["price"].head())

Confirmed by pandas.pydata.org

Did this fix it?

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.

Check
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.

Fix
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.

Verify
print(df.shape, df.columns.tolist())

Confirmed by pandas.pydata.org

Did this fix it?

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.

Check
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.

Fix
df = df.reset_index()
df["date"]
# or keep the index and read it directly
df.index

Verify

The name appears in df.columns and the selection works.

Verify
print("date" in df.columns)

Confirmed by pandas.pydata.org

Did this fix it?

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.

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.