Home > Software engineering >  Select & automate rename columns pandas dataframe
Select & automate rename columns pandas dataframe

Time:10-05

I searched before asking this but either I didn't understand the reply or the answer wasn't adapted to my case.

This is my df

With this code : gini.iloc[:, 2:].rename(columns=lambda x : x[:4])

I have the result that I want, preview here. To know, rename 2000 [YR2000] to 2000, same for the other columns.

But I want to assign this modification in my original df. When I add inplace = True in the rename function, I get a copy warning that I don't know how to resolve.

Secondly, I don't know how to assign this change to my original df, keeping my first two columns intact.

Thanks ! I hope I'm clear, it's my first time.

CodePudding user response:

This would be a fairly easy way:

cols = df.columns
renames = {col: col[:4] for col in cols[2:]}
df.rename(columns=renames, inplace=True)
  • Related