2

在 python 中执行一个热编码器后保留列名的最佳方法是什么?我所有的特征都是分类的,所以我喜欢下面:所以,导入数据集后,它看起来像下面

 PlaceID       Date  ...  BlockedRet  OverallSeverity
0    23620  1/10/2019  ...           1                1
1    13352  1/10/2019  ...           1                1
2    13674  1/10/2019  ...           1                1
3    13501  1/10/2019  ...           1                1
4    13675  1/10/2019  ...           1                1

[5 rows x 28 columns]

选择功能后,我想使用一个热编码器来转换它们,因为它们中的大多数都是分类的,我这样做之后的问题是:

from sklearn.preprocessing import LabelEncoder, OneHotEncoder

hotencode = OneHotEncoder(categorical_features=[0])
features = hotencode.fit_transform(features).toarray()

在此处输入图像描述 结果没有原始列名,如何使用相同的列名+0.,1,2,3 转换它们。

4

1 回答 1

6

这是一个简单的例子:

import pandas as pd

df = pd.DataFrame([
       ['green', 'Chevrolet', 2017],
       ['blue', 'BMW', 2015], 
       ['yellow', 'Lexus', 2018],
])
df.columns = ['color', 'make', 'year']

df

'''
    color       make  year  color_encoded  Color_0  Color_1  Color_2
0   green  Chevrolet  2017              1      0.0      1.0      0.0
1    blue        BMW  2015              0      1.0      0.0      0.0
2  yellow      Lexus  2018              2      0.0      0.0      1.0
'''

方法 1: 一个热编码器

from sklearn.preprocessing import LabelEncoder
le_color = LabelEncoder()
df['color_encoded'] = le_color.fit_transform(df.color)

from sklearn.preprocessing import OneHotEncoder
color_ohe = OneHotEncoder()

X = color_ohe.fit_transform(df.color_encoded.values.reshape(-1,1)).toarray()

dfOneHot = pd.DataFrame(X, columns = ["Color_"+str(int(i)) for i in range(X.shape[1])])
df = pd.concat([df, dfOneHot], axis=1)

df

'''
    color       make  year  color_encoded  Color_0  Color_1  Color_2
0   green  Chevrolet  2017              1      0.0      1.0      0.0
1    blue        BMW  2015              0      1.0      0.0      0.0
2  yellow      Lexus  2018              2      0.0      0.0      1.0
'''

参考:

https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html

方法2: 获取假人

df_final = pd.concat([df, pd.get_dummies(df["color"],prefix="color")], axis=1)


df_final

'''
    color       make  year  color_blue  color_green  color_yellow
0   green  Chevrolet  2017           0            1             0
1    blue        BMW  2015           1            0             0
2  yellow      Lexus  2018           0            0             1
'''

参考:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.get_dummies.html

于 2019-11-12T12:49:13.750 回答