Rename columns with a loop in Pandas

Viewed 2212

I need to rename all the columns of a dataframe (pandas) with ~100 columns. I created a list with all the new names stored and i need a handy function to rename them. Many solutions online are dealing "manually" be stating the old column name, which is not possible with this size.

I tried a simple for loop like:

for i in range(0,96):
    df.columns[i] = new_cols_list[i]

That is the way i would do it in r, but it throws an error:

"Index does not support mutable operations"

2 Answers

All you have to do is:

df.columns = new_cols_list

Use it only when you have to rename all columns. The new_col_list is the list containing the new names of columns with size equal to number of columns.

When you have to rename specific columns, then use 'rename' as shown in other answers.

Related