如何在sklearn中使用OneHotEncoder的输出?

Ber*_*ans 8 python classification pandas scikit-learn one-hot-encoding

我有一个带有2个分类变量的Pandas Dataframe,以及ID变量和目标变量(用于分类).我设法将分类值转换为OneHotEncoder.这导致稀疏矩阵.

ohe = OneHotEncoder()
# First I remapped the string values in the categorical variables to integers as OneHotEncoder needs integers as input
... remapping code ...

ohe.fit(df[['col_a', 'col_b']])
ohe.transform(df[['col_a', 'col_b']])
Run Code Online (Sandbox Code Playgroud)

但我不知道如何在DecisionTreeClassifier中使用这个稀疏矩阵?特别是当我想稍后在我的数据帧中添加一些其他非分类变量时.谢谢!

编辑 回复miraculixx的评论:我还尝试了sklearn-pandas中的DataFrameMapper

mapper = DataFrameMapper([
    ('id_col', None),
    ('target_col', None),
    (['col_a'], OneHotEncoder()),
    (['col_b'], OneHotEncoder())
])

t = mapper.fit_transform(df)
Run Code Online (Sandbox Code Playgroud)

但后来我得到了这个错误:

TypeError:类型不支持转换:(dtype('O'),dtype('int64'),dtype('float64'),dtype('float64')).

Gui*_*sch 13

我看到你已经在使用Pandas了,为什么不使用它的get_dummies功能呢?

import pandas as pd
df = pd.DataFrame([['rick','young'],['phil','old'],['john','teenager']],columns=['name','age-group'])
Run Code Online (Sandbox Code Playgroud)

结果

   name age-group
0  rick     young
1  phil       old
2  john  teenager
Run Code Online (Sandbox Code Playgroud)

现在用get_dummies编码

pd.get_dummies(df)
Run Code Online (Sandbox Code Playgroud)

结果

name_john  name_phil  name_rick  age-group_old  age-group_teenager  \
0          0          0          1              0                   0   
1          0          1          0              1                   0   
2          1          0          0              0                   1   

   age-group_young  
0                1  
1                0  
2                0
Run Code Online (Sandbox Code Playgroud)

实际上,您可以在Sklearn的DecisionTreeClassifier中使用新的Pandas DataFrame.

  • 谢谢Guiem Bosch,这很有效.但是,我必须指定仅在两列上使用get_dummies.如果我在Dataframe中留下了ID变量,我收到了内核死机的消息.所以下面的代码工作:pd.get_dummies(df [['col_a','col_b']]) (2认同)