how to rename columns in pandas using a list
Asked Answered
H

2

12

I have a dataframe (df) that has 44 columns and I want to rename columns 2:44. I have a list (namesList) of length 42 that has the new column names. I then try to rename my columns by using the list:

df.columns[2:len(df.columns)] = namesList

However I get the error:

TypeError: Index does not support mutable operations

Why do I get this error?

Hartzel answered 6/11, 2016 at 20:14 Comment(0)
B
18

You need generate new columns names - first and second value from old one and another from list:

df.columns = df.columns[:2].tolist() + namesList

Sample:

df = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})

print (df)
  A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3

namesList = ['K','L','M','N']
df.columns = df.columns[:2].tolist() + namesList
print (df)
   A  B  K  L  M  N
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3
Barong answered 6/11, 2016 at 20:15 Comment(2)
should we expect "Index does not support mutable operations" when trying to do this?Bazar
@Bazar - do you assign new list of columns names to columns? If yes, then not.Barong
C
1

I have come across renaming the first N column and last N columns. Replace the value for N according to your need.

1) To Rename Last N Columns (ignoring the first 2)

cols_to_update = df.columns[:N].tolist() + ['col2_new','col3_new']
df.columns = cols_to_update

2) To Rename First N columns (ignoring Last N )

cols_to_update = ['col3_new','col4_new'] + df.columns[N:].tolist()
df.columns = cols_to_update

3) Rename Columns in the middle

cols_to_update = df.columns[:N].tolist() + ['col2_new','col3_new'] + df.columns[Y:].tolist()
df.columns = cols_to_update

4) To rename all columns - Make sure the list you assign is the same length as df.columns.

list = ['col1_new','col2_new', 'col3_new','col4_new']
df.columns = list

You can find more examples @ Multiple ways to Rename Columns in pandas

Clachan answered 28/1, 2022 at 2:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.