gpt4 book ai didi

python - 如何在 pandas 的前 N ​​列添加后缀?

转载 作者:行者123 更新时间:2023-12-01 22:54:59 25 4
gpt4 key购买 nike

我想为前 N 列添加一个后缀。但我不能。

这是为所有列添加后缀的方法:

import pandas as pd

df = pd.DataFrame( {"name" : ["John","Alex","Kate","Martin"], "surname" : ["Smith","Morgan","King","Cole"],
"job": ["Engineer","Dentist","Coach","Teacher"],"Age":[25,20,25,30],
"Id": [1,2,3,4]})

df.add_suffix("_x")

这是结果:

    name_x    surname_x   job_x      Age_x   Id_x
0 John Smith Engineer 25 1
1 Alex Morgan Dentist 20 2
2 Kate King Coach 25 3
3 Martin Cole Teacher 30 4

但我想添加前 N 列,所以假设前 3 列。所需的输出是:

    name_x    surname_x   job_x      Age     Id
0 John Smith Engineer 25 1
1 Alex Morgan Dentist 20 2
2 Kate King Coach 25 3
3 Martin Cole Teacher 30 4

最佳答案

使用索引并获取切片来修改它们的子集:

df.columns = (df.columns[:3]+'_x').union(df.columns[3:], sort=False)

print(df)
name_x surname_x job_x Age Id
0 John Smith Engineer 25 1
1 Alex Morgan Dentist 20 2
2 Kate King Coach 25 3
3 Martin Cole Teacher 30 4

关于python - 如何在 pandas 的前 N ​​列添加后缀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73484206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com