简体   繁体   中英

How to change column names of last 7 columns of pandas dataframe?

I am running a loop and adding 7 new columns to an existing dataframe. After each iteration of the loop, I want to change column names of only the new columns added (ie last 7 columns). I have tried doing this using following line of code:

df.columns[len(df.columns)-6:len(df.columns)] = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7']

This line of code is not working and I am getting an error -

Index does not support mutable operations

I have looked up on various sites but none of the methods help my case. What can I do to change name of only last 7 columns?

Thanks.

You can copy the columns into a list with df.columns.tolist() , modify the list instead of df.columns itself, and then assign the list back to df.columns :

columns = df.columns.tolist()
columns[len(columns)-6:len(columns)] = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7']
df.columns = columns

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM