【问题标题】:OneHot vectors with feature names具有特征名称的 OneHot 向量
【发布时间】:2020-03-01 21:59:49
【问题描述】:

查看OneHotEncoder 的文档,似乎没有办法将特征名称包含为 OneHot 向量的前缀。有谁知道解决这个问题的方法?我错过了什么吗?

示例数据框:

df = pd.DataFrame({'a':['c1', 'c1', 'c2', 'c1', 'c3'], 'b':['c1', 'c4', 'c1', 'c1', 'c1']})

from sklearn.preprocessing import OneHotEncoder

onehot = OneHotEncoder()
onehot.fit(df)

onehot.get_feature_names()
array(['x0_c1', 'x0_c2', 'x0_c3', 'x1_c1', 'x1_c4'], dtype=object)

如果给编码器提供了一个数据帧,我希望有可能获得类似的东西:

array(['a_c1', 'a_c2', 'a_c3', 'b_c1', 'b_c4'], dtype=object)

【问题讨论】:

    标签: python pandas machine-learning scikit-learn


    【解决方案1】:

    您需要执行以下操作以包含来自 get_feature_name 的功能名称。

    onehot.get_feature_names(input_features=df.columns)
    

    输出:

    array(['a_c1', 'a_c2', 'a_c3', 'b_c1', 'b_c4'], dtype=object)
    

    每个文档:

    get_feature_name(self, input_features=None)
    返回输出特征的特征名称。

    参数:input_features:字符串列表,长度为n_features, 输入功能的可选字符串名称(如果可用)。默认, 使用“x0”、“x1”、……“xn_features”。

    返回: output_feature_names :字符串数组,长度 n_output_features

    【讨论】:

    • 啊,有办法!谢谢@scott :)
    • 出于确切原因,我已经更新了文档中的示例。看开发版文档here
    【解决方案2】:

    让我们创建一个包含 3 列的数据框,每列都有一些分类值。

    import pandas as pd
    from sklearn.preprocessing import OneHotEncoder
    
    df_dict= {'Sex' :['m', 'f' ,'m' ,'f'] , 'City' : ['C1' , 'C2' , 'C3' , 'C4'] , 'States' :['S1' , 'S2', 'S3', 'S4']}
    df = pd.DataFrame.from_dict(df_dict)
    cat_enc = OneHotEncoder(handle_unknown = 'ignore')
    transformed_array = cat_enc.fit_transform(df).toarray()
    transformed_df = pd.DataFrame(transformed_array , columns= cat_enc.get_feature_names(df.columns))
    transformed_df.head()
    

    我们将得到以下输出 -

    City_C1 City_C2 City_C3 City_C4 Sex_f   Sex_m   States_S1   States_S2   States_S3   States_S4
    0   1.0 0.0 0.0 0.0 0.0 1.0 1.0 0.0 0.0 0.0
    1   0.0 1.0 0.0 0.0 1.0 0.0 0.0 1.0 0.0 0.0
    2   0.0 0.0 1.0 0.0 0.0 1.0 0.0 0.0 1.0 0.0
    3   0.0 0.0 0.0 1.0 1.0 0.0 0.0 0.0 0.0 1.0
    

    【讨论】:

      猜你喜欢
      • 2022-11-07
      • 2022-11-25
      • 2016-01-15
      • 2020-12-10
      • 2022-11-27
      • 2019-08-10
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      相关资源
      最近更新 更多