You need to enable JavaScript to run this app. Python如何自动将DataFrame各列低频类别归为Others后生成指定数量哑变量
优惠活动
大模型
产品
解决方案
定价
更多

Python如何自动将DataFrame各列低频类别归为Others后生成指定数量哑变量

解决方案

核心逻辑分为两步:先对每个分类列做频率过滤,将出现频率排名top_n之外的类别统一替换为Others,再调用get_dummies生成哑变量,完全避免冗余列生成。

可直接复用的实现代码

1. 基础通用版(所有分类列统一保留N个高频类别)

import pandas as pd
import numpy as np

def get_top_n_dummies(df, top_n=3, replace_value='Others', categorical_cols=None):
    # 未指定处理列时,自动识别所有字符/分类类型列
    if categorical_cols is None:
        categorical_cols = df.select_dtypes(include=['object', 'category']).columns.tolist()
    
    df_processed = df.copy()
    for col in categorical_cols:
        # 提取当前列出现频率前top_n的类别
        top_categories = df_processed[col].value_counts().nlargest(top_n).index
        # 非top类别统一替换为Others
        df_processed[col] = np.where(df_processed[col].isin(top_categories), df_processed[col], replace_value)
    
    # 生成最终哑变量
    return pd.get_dummies(df_processed, columns=categorical_cols)

调用示例

# 生成测试用DataFrame
np.random.seed(42)
df = pd.DataFrame({
    'col1': np.random.choice(['A','B','C','D','E','F','G'], size=1000, p=[0.4,0.3,0.15,0.05,0.04,0.03,0.03]),
    'col2': np.random.choice(['X','Y','Z','M','N','O','P'], size=1000, p=[0.35,0.3,0.2,0.05,0.04,0.03,0.03]),
    'num_col': np.random.randint(1,10, size=1000) # 数值列会自动跳过处理
})

# 每列保留前3个高频类别,其余归为Others
result_df = get_top_n_dummies(df, top_n=3)

2. 自定义列版本(不同列可指定不同保留数量)

如果不同列需要保留的高频类别数量不同,可以用以下变体:

def get_custom_top_dummies(df, col_top_n: dict, replace_value='Others'):
    df_processed = df.copy()
    for col, top_n in col_top_n.items():
        top_categories = df_processed[col].value_counts().nlargest(top_n).index
        df_processed[col] = np.where(df_processed[col].isin(top_categories), df_processed[col], replace_value)
    return pd.get_dummies(df_processed, columns=col_top_n.keys())

# 调用示例:col1保留3个高频类,col2保留4个高频类
result_df = get_custom_top_dummies(df, col_top_n={'col1':3, 'col2':4})

效果说明

处理后每列只会生成top_n + 1个哑变量列(top_n个高频类+1个Others类),不会生成低频类别的冗余列,最终数据量可控。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 16:21:04