Milo
Milo

Reputation: 3

Renaming columns in a dataframe using a loop

Say I have a dataframe (df) which looks as given below enter image description here

It has columns 3 columns all named the same (L, L, L). I want to rename the columns as L1, L2 and L3 based on their column position. I expect the optput to look as given below.

enter image description here

I can do it using the code df.columns = ['Input', 'L1', 'L2', 'L3']

However, I believe a way must be available where I loop over all columns (or chosen columns) so that this can be automated for any dataframe.

Many thanks in advance for the responses.

Upvotes: 0

Views: 230

Answers (1)

Ynjxsjmh
Ynjxsjmh

Reputation: 29992

You use

df.columns = [f'{col}{i}' if col == 'L' else col for i, col in enumerate(df.columns)]

Upvotes: 1

Related Questions