繁体   English   中英

使用索引号同时更改 pandas 数据框中的多个列名(并非所有列名)

[英]Change multiple column names in pandas dataframe (not all colmn names) at the same time using index numbers

我已经使用这个成功更改了数据框中的单个列名:

df.columns=['new_name' if x=='old_name' else x for x in df.columns]

但是,我有很多列要更新(但不是全部 240 个),如果我能帮上忙,我不想为每个更改都写出来。

我试图在此线程中遵循@StefanK 的建议:

更改多个列名但不是全部 - Pandas Python

我的代码:

df.columns=[[4,18,181,182,187,188,189,190,203,204]]=['Brand','Reason','Chat_helpful','Chat_expertise','Answered_questions','Recommend_chat','Alternate_help','Customer_comments','Agent_category','Agent_outcome']

但我收到一条错误消息:

File "<ipython-input-17-2808488b712d>", line 3
    df.columns=[[4,18,181,182,187,188,189,190,203,204]]=['Brand','Reason','Chat_helpful','Chat_expertise','Answered_questions','Recommend_chat','Alternate_help','Customer_comments','Agent_category','Agent_outcome']
                   ^
SyntaxError: can't assign to literal

因此,在谷歌搜索错误并在这里阅读更多SO问题后,在我看来,它试图将数字读取为整数而不是索引? 不过我在这里不确定。

那么我该如何修复它才能将数字视为索引?! 我要替换的列名称每个至少有 10 个字长,所以我很想不必将它们全部输入! 我唯一的想法是以某种方式使用 iloc 但我要在这里进入新领域!

真的很感谢一些帮助

删除代码中 df.columns 之后的 '=' 并改用它:

df.columns.values[[4,18,181,182,187,188,189,190,203,204]]=['Brand','Reason','Chat_helpful','Chat_expertise','Answered_questions','Recommend_chat','Alternate_help','Customer_comments','Agent_category','Agent_outcome']

因为 index 不支持可变操作,将其转换为 numpy 数组,重新分配并设置回:

df = pd.DataFrame({
        'A':list('abcdef'),
         'B':[4,5,4,5,5,4],
         'C':[7,8,9,4,2,3],
         'D':[1,3,5,7,1,0],
         'E':[5,3,6,9,2,4],
         'F':list('aaabbb')
})

arr = df.columns.to_numpy()
arr[[0,2,3]] = list('RTG')
df.columns = arr
print (df)
   R  B  T  G  E  F
0  a  4  7  1  5  a
1  b  5  8  3  3  a
2  c  4  9  5  6  a
3  d  5  4  7  9  b
4  e  5  2  1  2  b
5  f  4  3  0  4  b

因此,对于您的数据使用:

idx = [4,18,181,182,187,188,189,190,203,204]
names = ['Brand','Reason','Chat_helpful','Chat_expertise','Answered_questions','Recommend_chat','Alternate_help','Customer_comments','Agent_category','Agent_outcome']

arr = df.columns.to_numpy()
arr[idx] = names
df.columns = arr

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM