How to Clean Up Column Headers in Pandas
Three ways to tidy messy DataFrame column names: a short custom function passed to df.rename(columns=...), skimpy’s clean_columns, and dataprep’s clean_headers. The custom function is the one you can reason about. skimpy is the one to call on a current Python, because dataprep is no longer maintained.
Clean headers with a custom function
A function passed to rename(columns=...) runs once for every column name. Mine keeps letters, digits, spaces and underscores, strips spaces at both ends, lowercases the name and turns the remaining spaces into underscores. Anything that is not a string, such as a missing name, passes through unchanged.
Here is an example DataFrame with a messy header:
import numpy as np
import pandas as pd
df = pd.DataFrame(
{
"ISBN": [9781455582341],
"book Title": ["How Google Works"],
"Author ": ["Eric Schmidt, Jonathan Rosenberg"],
"Publication (year)": [2014],
"éditeur": ["Grand Central Publishing"],
"Number_Of_Pages": [305],
"RATING": [4.06],
}
)
df
And here is the function:
def clean_headers(val):
if isinstance(val, str):
# remove special chars (but keep spaces and underscores)
val = "".join(char for char in val if char.isalnum() or char in (" ", "_"))
# convert to snake case
val = val.strip().lower().replace(" ", "_")
return val
else:
return val
df_clean = df.rename(columns=clean_headers)
Headers such as book Title, Author with a trailing space and Publication (year) become book_title, author and publication_year. Accented letters such as the é in éditeur count as letters, so they stay. I tested it with pandas 3.1. The output shows the header before and after the cleanup:
ISBN book Title Author Publication (year) éditeur Number_Of_Pages RATING
0 9781455582341 How Google Works Eric Schmidt, Jonathan Rosenberg 2014 Grand Central Publishing 305 4.06
isbn book_title author publication_year éditeur number_of_pages rating
0 9781455582341 How Google Works Eric Schmidt, Jonathan Rosenberg 2014 Grand Central Publishing 305 4.06
Use dataprep’s clean_headers
dataprep’s clean_headers handles headers that a short function does not: duplicate names get a numbered suffix, missing names become header, and accents are removed. The catch is age. dataprep has not had a release since 2022 and only installs on Python versions before 3.11, so on a current Python use skimpy below.
Install it with:
pip install -U dataprep
Import clean_headers from the dataprep clean module. It converts to snake case by default, the case argument switches to other styles such as camel case, and the replace argument takes a dictionary of characters or words to swap. Here it runs on an even messier DataFrame:
df_messy = pd.DataFrame(
{
"ISBN": [9781455582341],
"isbn": [1455582328],
"bookTitle": ["How Google Works"],
"__Author": ["Eric Schmidt, Jonathan Rosenberg"],
"Publication (year)": [2014],
"éditeur": ["Grand Central Publishing"],
"Number_Of_Pages": [305],
"★ Rating": [4.06],
np.nan: ["How Google Works"],
None: ["Eric Schmidt, Jonathan Rosenberg"],
"N/A": [2014],
}
)
from dataprep.clean import clean_headers
# Default snake case
clean_headers(df_messy).head()
Column Headers Cleaning Report:
11 values cleaned (100.0%)
isbn isbn_1 book_title author publication_year editeur number_of_pages rating header header_1 n_a
0 9781455582341 1455582328 How Google Works Eric Schmidt, Jonathan Rosenberg 2014 Grand Central Publishing 305 4.06 How Google Works Eric Schmidt, Jonathan Rosenberg 2014
Use skimpy’s clean_columns
skimpy is a lighter, maintained library that works on current Python versions. Its clean_columns function comes from dataprep, so it has the same options for the case and for replacing values. Install it with:
pip install skimpy
Import clean_columns from skimpy. Unlike my custom function, it also turns éditeur into editeur:
from skimpy import clean_columns
df_clean = clean_columns(df) # snake_case by default
df_clean = clean_columns(df, case="camel") # bookTitle, numberOfPages, ...
On the messy DataFrame it gives the same result as dataprep, and the options change the case or swap specific characters, for example PUBLISHER and STAR_RATING with the replace dictionary below. Clean headers pay off as soon as you select columns by name or read messy Excel files with inconsistent titles. I use the cleanup as one step of a method chain in my complete pandas tutorial.
from skimpy import clean_columns
clean_columns(df_messy).head()
clean_columns(df_messy, case="title").head()
clean_columns(
df_messy, case="const", replace={"éditeur": "publisher", "★": "star"}
).head()
