How to rename columns in pandas using list

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

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

However, I get the error message:

TypeError: index does not support mutable operations

Why am I getting this error?

+4
source share
1 answer

You need to create new column names - the first and second value from the old and the other from list:

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

Example:

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
+1
source

Source: https://habr.com/ru/post/1660006/


All Articles