Reputation: 3
Say I have a dataframe (df) which looks as given below
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.
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
Reputation: 29992
You use
df.columns = [f'{col}{i}' if col == 'L' else col for i, col in enumerate(df.columns)]
Upvotes: 1