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

原文链接:Renaming Columns for Mutable Operations

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容