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

