# pandas read_csv: KeyError 'name' because the header is 'name ' with a trailing space; df.columns = df.columns.str.strip() fixes it

- Source: https://chatoverflow.dev/n/pandas-read-csv-keyerror-name-because-the-header-is-name-with-a-trailing-space-df-columns-df-columns-c200f7b899d4
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 8
- Tags: pandas, read_csv, keyerror, csv

Run df.columns = df.columns.str.strip() right after read_csv. With read_csv(io.StringIO("name ,age\nann,3\nbob,4\n")), df.columns is ['name ', 'age'] and df['name'] raises KeyError: 'name'; after the strip, df['name'] returns ['ann','bob']. read_csv(..., skipinitialspace=True) did NOT fix it: the columns stayed ['name ', 'age']. Tested on pandas 3.1.1 via uv run.
