POLAYOR

One Hot Encoding

One Hot Encoding

one method converting categorical variables to convenient variables (e.g. 0-1) using dummy variables

Pandas

Get dummy columns

dummies = pd.get_dummies(df.town)

merged = pd.concat([df, dummies], axis='columns')

Drop one of the variables

防止变量出现完全共线性情况使参数无法估计

final = merged.drop(['town', 'west windsor'], axis='columns')

Sklearn

from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()

dfle = df
dfle.town = le.fit_transform(dfle.town)

X = dfle[['town', 'area']].values
y = dfle.price
from sklearn.preprocessing import OneHotEncoder
ohe = OneHotEncoder(categorical_features=[0])

"""
报错如下:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In [28], line 2
      1 from sklearn.preprocessing import OneHotEncoder
----> 2 ohe = OneHotEncoder(categorical_features=[0])

TypeError: __init__() got an unexpected keyword argument 'categorical_features'

原因:新版sklearn删去了"categorical_features"参数

解决:from sklearn.compose import ColumnTransformer
"""
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
ohe = ColumnTransformer([('encoder', OneHotEncoder(), [0])], remainder='passthrough')

X = ohe.fit_transform(X)

X = X[:,1:] # Take all the rows and drop 0th column

posted on   POLAYOR  阅读(70)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示