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

Pandas如何修改除指定列外的列名并批量添加后缀

实现方法

你可以通过两种常用方式完成列名批量处理:


方法1:直接修改列名属性

直接遍历列名做条件判断处理,代码最简洁:

import pandas as pd

# 定义不需要处理的列列表
skip = ['ID', 'Type']

# 批量处理列名
df.columns = [
    col if col in skip 
    else col.lower().replace(' ', '_') + '_filled' 
    for col in df.columns
]

方法2:使用rename方法处理

适合不想修改原始DataFrame的场景,会返回处理后的新DataFrame:

skip = ['ID', 'Type']

df = df.rename(
    columns=lambda col: col if col in skip 
    else col.lower().replace(' ', '_') + '_filled'
)

验证结果

处理后执行print(df.columns)可以得到符合要求的输出:

Index(['ID', 'col_a_filled', 'col_b_filled', 'col_c_filled', 'col_d_filled', 'col_e_filled', 'col_f_filled', 'Type'], dtype='object')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 20:09:02