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... ?
Asked
Active
Viewed 154 times
1 Answers
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
-
Thank you norie. However when I print(df.columns) I get an error. AttributeError: 'list' object has no attribute 'columns' – ROGAN RICHEART Mar 10 '21 at 16:35
-
I think I left out some info. I want to rename the 'column names' in the dataframe. Not the values in the columns. – ROGAN RICHEART Mar 10 '21 at 16:41
-
The code I posted does change the column names in the dataframe, I'll add the output from the code I posted to my answer. – norie Mar 10 '21 at 16:42
-
I found where I needed to make the adjustment. Thanks again norie. – ROGAN RICHEART Mar 10 '21 at 16:44
-
Just saw your comment and that was the same change I made. Awesome. Have a great day norie. – ROGAN RICHEART Mar 10 '21 at 16:45
-
What change? :) I didn't really change the 'core' of the code, I added some print statements to illustrate what the code was doing. Any way, If you've got it working... – norie Mar 10 '21 at 16:47
-
I would vote but this was my first question on here, so no reputation to be allowed to vote. – ROGAN RICHEART Mar 11 '21 at 19:37