Remove or replace spaces in column names

  • To remove white spaces:
  1. To remove white space everywhere:
df.columns = df.columns.str.replace(' ', '')
  1. To remove white space at the beginning of string:
df.columns = df.columns.str.lstrip()
  1. To remove white space at the end of string:
df.columns = df.columns.str.rstrip()
  1. To remove white space at both ends:
df.columns = df.columns.str.strip()
  • To replace white spaces with other characters (underscore for instance):
  1. To replace white space everywhere
df.columns = df.columns.str.replace(' ', '_')
  1. To replace white space at the beginning:
df.columns = df.columns.str.replace('^ +', '_')
  1. To replace white space at the end:
df.columns = df.columns.str.replace(' +$', '_')
  1. To replace white space at both ends:
df.columns = df.columns.str.replace('^ +| +$', '_')

All above applies to a specific column as well, assume you have a column named col, then just do:

df[col] = df[col].str.strip()  # or .replace as above

Commands can be chained

df.columns = df.columns.str.strip().str.replace(' ', '_')

Leave a Comment