Skip to content

Instantly share code, notes, and snippets.

@ebressert
Created February 8, 2015 06:37
Show Gist options
  • Save ebressert/03f90f8f189439dc993b to your computer and use it in GitHub Desktop.
Save ebressert/03f90f8f189439dc993b to your computer and use it in GitHub Desktop.
def column_cleaner(df, inplace=False):
"""
Clean up column names where white spaces are trimmed and replaced.
All column names are lowercased for sanity.
"""
orig_cols = df.columns
new_cols = []
for col in orig_cols:
new_cols.append("".join([c if c.isalnum() else "_" for c in col.strip()]).lower())
record = dict(zip(orig_cols, new_cols))
if not inplace:
df = df.rename(columns=record, inplace=inplace)
return df
else:
df.rename(columns=record, inplace=inplace)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment