1

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 (i.e. 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?

Henry Ecker
  • 31,792
  • 14
  • 29
  • 50

1 Answers1

1

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
richardec
  • 14,202
  • 6
  • 23
  • 49
  • 2
    Python supports negative indexing so `columns[-6:] = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7']` is fine. Also just `df.columns.values[-6:] = ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7']` works. – Henry Ecker Nov 20 '21 at 02:45