I'm trying to rename columns in a df with a for-loop.
Where am I going wrong with below?
for col_name in df:
df.rename(columns={col_name:col_name '_x'})
df now:
| A | B | C |
|---|---|---|
| - | - | - |
Desired result:
| Ax | Bx | Cx |
|---|---|---|
| - | - | - |
CodePudding user response:
You can use list comprehension with pandas.DataFrame.columns :
df.columns = [col "x" for col in df.columns]
Or simply :
df.columns = df.columns "x"
CodePudding user response:
Try to add inplace=True parameter:
for col_name in df:
df.rename(columns={col_name: col_name "_x"}, inplace=True)
Prints:
A_x B_x C_x
0 - - -
I recommend to look at .add_suffix() method:
df = df.add_suffix("_x")
