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
Asked By: geaa

||

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")
Answered By: Andrej Kesely

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"
Answered By: abokey
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.