0

I want to use the replace function to remove spaces. Is there a way to do this without hardcoding the actual name or using df.columns[0], df.columns[1] and so on... ?

1 Answers1

0

If you wanted to replace all the spaces in the column names you could use this.

Code

import pandas as pd

df = pd.DataFrame({'Column A ':[1,2,2,3], 'Column B ':[4,8,9,12]})

print(df)
print(df.columns)

df.columns = [colname.replace(' ', '') for colname in df.columns]

print(df)
print(df.columns)

Code output

   Column A   Column B 
0          1          4
1          2          8
2          2          9
3          3         12
Index(['Column A ', 'Column B '], dtype='object')
   ColumnA  ColumnB
0        1        4
1        2        8
2        2        9
3        3       12
Index(['ColumnA', 'ColumnB'], dtype='object')

If that's not you want change replace in the list comprehension to whatever method will return the names as you want them, e.g. rstrip to remove all whitespace characters at the end.

norie
  • 9,609
  • 2
  • 11
  • 18