pandas 重命名多个列
dataframe 是一个二维标签数据结构。它是一种大小可变的异构数据结构。
dataframe 包含称为行和列的标记轴。
本教程将讨论使用 python 重命名 dataframe 的多个列的不同方法。
使用 pandas 的 rename()
函数来重命名多列
pandas 库提供了用于重命名 dataframe 列的 rename()
函数。
rename()
函数采用 mapper
,这是一种类似字典的数据结构,其中包含重命名列作为键,名称作为值。它返回一个 dataframe。
就地修改也可以通过设置 inplace = true
来完成。
语法:
pandas.rename(mapper)
以下是使用 rename()
方法重命名多个列的步骤。
-
导入 pandas 库。
-
将 mapper 传递给
rename()
方法。 -
rename()
方法将返回一个数据框,该列重命名。 -
打印 dataframe。
以下代码是上述方法的实现。
# importing pandas library
import pandas as pd
# creating a dataframe
df = pd.dataframe(
{
"course": ["c", "python", "java"],
"mentor": ["alex", "alice", "john"],
"cost": [1000, 2000, 3000],
}
)
# dataframe before renaming
print("\n before renaming")
print(df)
# renaming the multiple columns by index
df = df.rename(columns={df.columns[0]: "subject", df.columns[2]: "price"})
# dataframe after renaming
print("\n after renaming")
print(df)
重命名前的输出:
course | mentor | cost |
---|---|---|
c | alex | 1000 |
python | alice | 2000 |
java | john | 3000 |
重命名后的输出:
subject | mentor | price |
---|---|---|
c | alex | 1000 |
python | alice | 2000 |
java | john | 3000 |
使用 dataframe.column.values
使用 pandas 重命名多个列
dataframe.column.values
将返回所有列名,我们可以使用索引来修改列名。column.values
将返回一个索引数组。
以下是使用此方法重命名多个列的步骤:
- 导入 pandas 库。
- 使用
dataframe.column.values
检索列名数组。 - 通过传递索引来更改列的名称。
- 打印数据框。
以下代码是上述方法的实现。
# importing pandas library
import pandas as pd
# creating a dataframe
df = pd.dataframe(
{
"course": ["c", "python", "java"],
"mentor": ["alex", "alice", "john"],
"cost": [1000, 2000, 3000],
}
)
# dataframe before renaming
print("\n before renaming")
print(df)
# renaming the multiple columns by index
df.columns.values[0:2] = ["subject", "teacher"]
# dataframe after renaming
print("\n after renaming")
print(df)
重命名前的输出:
course | mentor | cost |
---|---|---|
c | alex | 1000 |
python | alice | 2000 |
java | john | 3000 |
重命名后的输出:
subject | teacher | cost |
---|---|---|
c | alex | 1000 |
python | alice | 2000 |
java | john | 3000 |
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
pandas dataframe dataframe.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:python
-
dataframe.shift() 函数是将 dataframe 的索引按指定的周期数进行移位。
python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:python
-
python pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:python
-
pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 dataframe 中。
pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:python
-
本教程介绍了如何在 pandas 中使用 dataframe.merge()方法合并两个 dataframes。
pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:python
-
本教程介绍了如何使用 python 中的 loc 和 iloc 从 pandas dataframe 中过滤数据。
在 python 中将 pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:python
-
了解如何在 python 中将 pandas 系列日期时间转换为字符串