How can I strip the whitespace from Pandas DataFrame headers?
I am parsing data from an Excel file that has extra white space in some of the column headings.
When I check the columns of the resulting dataframe, like so:
The result looks like this:
Index(['Year', 'Month ', 'Value'])
Consequently, I can't run
Because it will tell me the column is not found, as I asked for "Month", not "Month ".
My question, then, is how can I strip out the unwanted white space from the column headings?
You can give functions to the
rename method. The
str.strip() method should do what you want.
In : df Out: Year Month Value 0 1 2 3 [1 rows x 3 columns] In : df.rename(columns=lambda x: x.strip()) Out: Year Month Value 0 1 2 3 [1 rows x 3 columns]