DEV Community

GharamElhendy
GharamElhendy

Posted on

Renaming Columns for Mutable Operations

The simple syntax used to change a column name is like this:

This is with the following info in mind:
dataframe name is file and we want to modify the 9th column's name


file_df.columns[8] = 'new_column_name'
Enter fullscreen mode Exit fullscreen mode

However, index doesn't support mutable operations, and that's why we'll have to use a different syntax for this modification, which is as follows:

file_df.rename(columns={'old-column-name':'new_column_name'}, inplace=True)
Enter fullscreen mode Exit fullscreen mode

There's another method that's a little longer, and it goes as follows:

new_labels = list(file_df.columns)
new_labels[8] = 'new_column_name'
file_df.columns = new_labels
Enter fullscreen mode Exit fullscreen mode

Note: Using this method, we're reassigning the entire thing to a new list

Top comments (0)