-1

I assign the column index of a dataframe to an object.

Object1 = df.columns

Next, I try to change the 2nd element of this list.

Object1[1]='Fred'

I am getting the following error when I attempt to change the element of a list.

'TypeError: Index does not support mutable operations'

I simply expect the second element (column) name to be "Fred".

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
WON_Eric
  • 11
  • 3
  • not sure I get it right, are you trying to change the name of the column? are you using pandas? – adhg Jun 05 '19 at 19:55
  • The values *in* the dataframe are mutable, but the indices and column names are not. To change column names, you'll have to add a new column with that name and drop the old one – C.Nivs Jun 05 '19 at 19:55
  • I'm trying to change the name of a column. The actual code is a for loop, where I am trying to rename a particular column each type the loop executes. I get the same error so I showed the simple example. – WON_Eric Jun 05 '19 at 19:59

2 Answers2

4

The answer to your question. Columns are an index, and they are immutable. You can, however do something like this:

test = df.columns.values
test[1] = 'Fred'
df.columns = test

Or use the dedicated method pandas.DataFrame.rename() like this:

df.rename(columns={df.columns[1]: "Fred"}, inplace=True)
FabienP
  • 3,018
  • 1
  • 20
  • 25
krflol
  • 1,105
  • 7
  • 12
0

Try the following:

Object1 = df.columns.values
Object1[1]='Fred'
M. Shen
  • 126
  • 1
  • 4