rename columns with loop
Question:
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
–
–
–
Answers:
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")
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"
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 |
---|---|---|
– | – | – |
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")
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"