【问题标题】:OneHotEncoder only a single feature which is stringOneHotEncoder 只有一个特征,它是字符串
【发布时间】:2018-08-06 04:46:49
【问题描述】:

我希望将我仅有的一项功能转换为单独的二进制功能:

df["pattern_id"]
Out[202]: 
0       3
1       3
...
7440    2
7441    2
7442    3
Name: pattern_id, Length: 7443, dtype: int64 
df["pattern_id"]
Out[202]: 
0       0 0 1
1       0 0 1
...
7440    0 1 0
7441    0 1 0
7442    0 0 1
Name: pattern_id, Length: 7443, dtype: int64 

我想用OneHotEncoder,数据是int,所以不需要编码:

onehotencoder = OneHotEncoder(categorical_features=["pattern_id"])
df = onehotencoder.fit_transform(df).toarray()

ValueError: could not convert string to float: 'http://www.zaragoza.es/sedeelectronica/'

有趣的是,我收到一个错误...sklearn 尝试编码另一列,而不是我想要的。

我们必须将 pattern_id 编码为整数值

我使用了这个链接:Issue with OneHotEncoder for categorical features

#transform the pattern_id feature to int
encoding_feature = ["pattern_id"]
enc = LabelEncoder()
enc.fit(encoding_feature)
working_feature = enc.transform(encoding_feature)
working_feature = working_feature.reshape(-1, 1)
ohe = OneHotEncoder(sparse=False)


#convert the pattern_id feature to separate binary features
onehotencoder = OneHotEncoder(categorical_features=working_feature, sparse=False)
df = onehotencoder.fit_transform(df).toarray()

我得到同样的错误。我做错了什么?

编辑

来源: https://github.com/martin-varbanov96/scraper/blob/master/logo_scrape/logo_scrape/analysis.py

df
Out[259]: 
      found_img  is_http                                           link_img  \
0          True        0                                  img/aahoteles.svg   
//www.zaragoza.es/cont/paginas/img/sede/logo_e...   

      pattern_id                                       current_link  site_id  \
0              3             https://www.aa-hoteles.com/es/reservas        3   
6              3      https://www.aa-hoteles.com/es/ofertas-hoteles        3   
7              2           http://about.pressreader.com/contact-us/        4   
8              3           http://about.pressreader.com/contact-us/        4   

      status                                   link_id  
0        200               https://www.aa-hoteles.com/  
1        200               https://www.365travel.asia/  
2        200               https://www.365travel.asia/  
3        200               https://www.365travel.asia/  
4        200               https://www.aa-hoteles.com/  
5        200               https://www.aa-hoteles.com/  
6        200               https://www.aa-hoteles.com/  
7        200              http://about.pressreader.com  
8        200              http://about.pressreader.com  
9        200               https://www.365travel.asia/  
10       200               https://www.365travel.asia/  
11       200               https://www.365travel.asia/  
12       200               https://www.365travel.asia/  
13       200               https://www.365travel.asia/  
14       200               https://www.365travel.asia/  
15       200               https://www.365travel.asia/  
16       200               https://www.365travel.asia/  
17       200               https://www.365travel.asia/  
18       200              http://about.pressreade 

[7443 rows x 8 columns]

【问题讨论】:

    标签: python python-3.x machine-learning scikit-learn data-science


    【解决方案1】:

    如果您查看OneHotEncoder 的文档,您会发现categorical_features 参数需要“全部”或索引数组或掩码不是字符串。您可以通过更改为以下几行来使您的代码工作

    import pandas as pd
    from sklearn.preprocessing import OneHotEncoder
    # Create a dataframe of random ints
    df = pd.DataFrame(np.random.randint(0, 4, size=(100, 4)),
                      columns=['pattern_id', 'B', 'C', 'D'])
    onehotencoder = OneHotEncoder(categorical_features=[df.columns.tolist().index('pattern_id')])
    df = onehotencoder.fit_transform(df)
    

    不过,df 将不再是 DataFrame,我建议直接使用 numpy 数组。

    【讨论】:

    • 我无法更改数据类型,顺便说一句,仍然不起作用
    • 您使用的是什么版本的 sklearn?我在发布答案之前测试了代码,它工作正常。我将使用我使用的完整测试来扩展我的答案。你是什​​么意思你不能改变数据类型?无论如何,数据已经在 pandas 后端的一个 numpy 数组中了。
    • 除了pattern还有其他栏目,我会发帖更新
    • 对话有点长,我可以移步SO chat 讨论一下
    【解决方案2】:

    你也可以这样做

    import pandas as pd
    from sklearn.preprocessing import OneHotEncoder
    onehotenc = OneHotEncoder()
    X = onehotenc.fit_transform(df.required_column.values.reshape(-1, 1)).toarray()
    

    我们需要重塑列,因为fit_transform 需要一个二维数组。然后你可以将列添加到这个 numpy 数组中,然后将它与你的 DataFrame 合并。

    从这个链接看到here

    【讨论】:

      【解决方案3】:

      sklearn documentation here 中详细介绍了使用不同列类型的推荐方法。

      代表性例子:

      numeric_features = ['age', 'fare']
      numeric_transformer = Pipeline(steps=[('scaler', StandardScaler())])
      
      categorical_features = ['embarked', 'sex', 'pclass']
      categorical_transformer = OneHotEncoder(handle_unknown='ignore')
      
      preprocessor = ColumnTransformer(
          transformers=[
              ('num', numeric_transformer, numeric_features),
              ('cat', categorical_transformer, categorical_features)])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-08-18
        • 1970-01-01
        • 1970-01-01
        • 2015-09-28
        • 1970-01-01
        • 2020-03-26
        • 1970-01-01
        相关资源
        最近更新 更多