簡體   English   中英

在 python 中執行 OneHotEncoder 后保留列名的最佳方法是什么?

[英]what is the best way to keep columns names after doing OneHotEncoder in python?

在 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 轉換它們。

這是一個簡單的例子:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM