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

如何实现DataFrame中one-hot向量的逆操作(get_dummies反向还原)

实现pandas.get_dummies的逆操作(还原原始分类列)

当然有可行的方法,核心思路是识别one-hot编码对应的原始列分组,通过提取激活列的名称前缀/后缀来还原分类值,以下是具体实现方案:

示例场景准备

先构造包含两个分类特征的原始DataFrame,并执行one-hot编码:

import pandas as pd

# 原始分类数据
df_original = pd.DataFrame({
    'color': ['red', 'blue', 'red', 'green', None],
    'size': ['S', 'M', 'L', 'M', 'S']
})

# 执行one-hot编码(保留NaN的编码列,设置dummy_na=True)
df_encoded = pd.get_dummies(df_original, columns=['color', 'size'], dummy_na=True)

方法1:已知原始分类列名(最直接)

如果明确知道原始的分类列名(比如color和size),可以直接筛选对应前缀的one-hot列,通过idxmax找到激活列,再去除前缀还原原始值:

# 还原color列
df_encoded['color'] = df_encoded.filter(like='color_').idxmax(axis=1).str.replace('color_', '')
# 处理还原后的NaN值
df_encoded['color'] = df_encoded['color'].replace('nan', pd.NA)

# 还原size列
df_encoded['size'] = df_encoded.filter(like='size_').idxmax(axis=1).str.replace('size_', '')
df_encoded['size'] = df_encoded['size'].replace('nan', pd.NA)

# 移除one-hot编码列,得到还原后的DataFrame
df_restored = df_encoded.drop(df_encoded.filter(regex='^(color_|size_)').columns, axis=1)

方法2:未知原始分类列名(自动识别)

如果不清楚原始列名,可以通过one-hot列的前缀(get_dummies默认用原始列名作为前缀)自动识别分组,批量还原:

# 提取所有one-hot列的原始列名前缀
original_col_names = list(set(col.split('_')[0] for col in df_encoded.columns if '_' in col))

# 批量还原每个原始分类列
for col in original_col_names:
    # 找到对应前缀的one-hot列,提取激活列名称并去除前缀
    df_encoded[col] = df_encoded.filter(like=f'{col}_').idxmax(axis=1).str.replace(f'{col}_', '')
    # 还原NaN值
    df_encoded[col] = df_encoded[col].replace('nan', pd.NA)

# 移除one-hot编码列
df_restored = df_encoded.drop(df_encoded.filter(regex='_').columns, axis=1)

注意事项

  • 如果执行get_dummies时自定义了prefix_sep(分隔符),需要在str.replace和split时对应修改分隔符;
  • 如果编码时没有设置dummy_na=True,原始数据中的NaN会被忽略,还原时无法恢复这部分缺失值;
  • 该方法仅适用于get_dummies生成的标准one-hot编码(即每个分类值对应一列,每行仅有一个激活值)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:40:22