首页 > 解决方案 > 使用索引号同时更改 pandas 数据框中的多个列名(不是所有列名)

问题描述

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

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 但我要在这里进入新的领域!

非常感谢一些帮助

标签: pythonpandas

解决方案


删除代码中 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']

推荐阅读