You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何仅为DataFrame的指定列添加前缀

Pandas列名添加前缀报错修复方案

报错原因

pandas的DataFrame.columns是不可变的Index对象,不支持直接对切片位置赋值修改,这就是你收到Index does not support mutable operations报错的根本原因。

可选实现方案

以下3种方案均可实现需求,按需选择即可:

  • 方案1:使用rename方法精准修改指定列(最稳妥,不依赖列的位置)
# 若要将Ind_作为前缀用下方写法,作为后缀则调整为col + 'Ind_'
df = df.rename(columns={'D': 'Ind_D', 'E': 'Ind_E'})
  • 方案2:先将列名转为列表修改后再回写(适合明确要修改最后两列的场景)
new_cols = df.columns.tolist()
new_cols[-2:] = [f'Ind_{col}' for col in new_cols[-2:]]
df.columns = new_cols
  • 方案3:用列表推导式批量判断修改(适合需要批量筛选多列添加前缀的场景)
target_cols = ['D', 'E']
df.columns = [f'Ind_{col}' if col in target_cols else col for col in df.columns]

内容的提问来源于stack exchange,提问作者Jiamei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 07:27:04