深度阅读

How to Rename a Column in Pandas

作者
作者
2023年08月22日
更新时间
11.84 分钟
阅读时间
0
阅读量

There are multiple ways to rename a column in Pandas. Here are three common methods:

  1. Using the rename() method:
df.rename(columns={'old_name':'new_name'}, inplace=True)
  1. Assigning a new list of column names to df.columns:
df.columns = ['new_name1', 'new_name2', 'new_name3', ...]

Note that in each of these methods, the inplace=True parameter is used to modify the original DataFrame. If inplace is not used, a new DataFrame with the modified columns will be returned. Additionally, if you want to rename multiple columns at once, you can pass in a dictionary to the rename() method with the old and new column names as key-value pairs.

Here’s an example of how to use the rename() method to rename a single column in Pandas:

import pandas as pd

# create a sample DataFrame
df = pd.DataFrame({'old_name': [1, 2, 3], 'other_column': ['a', 'b', 'c']})

# rename the 'old_name' column to 'new_name'
df.rename(columns={'old_name': 'new_name'}, inplace=True)

# print the modified DataFrame
print(df)

This will output:

   new_name other_column
0         1            a
1         2            b
2         3            c

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。