- To remove white space everywhere:
df.columns = df.columns.str.replace(' ', '')
- To remove white space at the beginning of string:
df.columns = df.columns.str.lstrip()
- To remove white space at the end of string:
df.columns = df.columns.str.rstrip()
- To remove white space at both ends:
df.columns = df.columns.str.strip()
- To replace white spaces with other characters (underscore for instance):
- To replace white space everywhere
df.columns = df.columns.str.replace(' ', '_')
- To replace white space at the beginning:
df.columns = df.columns.str.replace('^ +', '_')
- To replace white space at the end:
df.columns = df.columns.str.replace(' +$', '_')
- 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(' ', '_')
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…