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

如何将多列转换为哑变量?对industryCode列执行独热编码并保留其他列

实现industryCode列的独热编码并保留其他列

原始数据

datewindCodeindustryCode
2022.08.01000001.SZ1101
2022.08.02000002.SZ1102
2022.08.03000003.SZ1103

需求:对industryCode列执行独热编码(One-Hot Encoding),同时保留date和windCode列。

实现代码(Python Pandas)

import pandas as pd

# 构造原始数据
df = pd.DataFrame({
    'date': ['2022.08.01', '2022.08.02', '2022.08.03'],
    'windCode': ['000001.SZ', '000002.SZ', '000003.SZ'],
    'industryCode': ['1101', '1102', '1103']
})

# 执行独热编码,保留其他列
# 使用prefix=''和prefix_sep=''让编码后的列名直接为industryCode的取值
df_encoded = pd.get_dummies(df, columns=['industryCode'], prefix='', prefix_sep='')

# 输出结果
print(df_encoded)

转换后结果

datewindCode110111021103
2022.08.01000001.SZ100
2022.08.02000002.SZ010
2022.08.03000003.SZ001

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 22:00:01