Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to rename columns in pandas using a list

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?

like image 227
Kevin Sun Avatar asked Nov 06 '16 20:11

Kevin Sun


People also ask

How do I rename a column in a DataFrame list?

Rename Columns with List using set_axis() Alternatively, you can use DataFrame. set_axis() method to rename columns with list. use inplace=True param to rename columns on the existing DataFrame object.

How do I rename a column in Pandas?

One way of renaming the columns in a Pandas Dataframe is by using the rename() function. This method is quite useful when we need to rename some selected columns because we need to specify information only for the columns which are to be renamed.

How do I rename multiple column names?

To change multiple column names by name and by index use rename() function of the dplyr package and to rename by just name use setnames() from data. table . From R base functionality, we have colnames() and names() functions that can be used to rename a data frame column by a single index or name.

How do I change a column name in Pandas CSV?

Pandas has a built-in function called rename() to change the column names.


1 Answers

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
like image 52
jezrael Avatar answered Oct 12 '22 23:10

jezrael