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

如何对DataFrame中除Target外的列名进行匿名化处理

匿名化非Target列名的实现方法

方法一:直接构造新列名列表

先筛选出非Target的列,生成对应的col1/col2格式匿名列名,再替换原DataFrame的列名:

import pandas as pd

df = pd.DataFrame({"IsCool": [0, 1, 0, 1], 
                   "IsTall": [1, 1, 1, 0], 
                   "IsHappy": [0, 0, 0, 1], 
                   "Target": [1, 0, 0, 1]})

# 提取非Target的列
non_target_cols = df.columns[df.columns != 'Target']
# 生成匿名列名
anon_cols = [f'col{i+1}' for i in range(len(non_target_cols))]
# 组合新列名:匿名列 + Target
df.columns = anon_cols + ['Target']

print(df)

运行输出:

col1  col2  col3  Target
0     0     1     0       1
1     1     1     0       0
2     0     1     0       0
3     1     0     1       1

方法二:字典映射重命名列

通过创建列名映射字典,只针对性修改非Target的列,更灵活:

import pandas as pd

df = pd.DataFrame({"IsCool": [0, 1, 0, 1], 
                   "IsTall": [1, 1, 1, 0], 
                   "IsHappy": [0, 0, 0, 1], 
                   "Target": [1, 0, 0, 1]})

# 生成列名映射:非Target列对应col1、col2...
rename_map = {col: f'col{i+1}' for i, col in enumerate(df.columns[df.columns != 'Target'])}
# 批量重命名列
df.rename(columns=rename_map, inplace=True)

print(df)

两种方法都能达到预期效果,可根据实际场景选择:方法一适合快速替换全部列名,方法二更便于后续调整匿名规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 23:50:14