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
相关产品推荐
相关产品推荐

