One-Hot-Encode 分类变量并同时缩放连续变量 [英] One-Hot-Encode categorical variables and scale continuous ones simultaneouely
本文介绍了One-Hot-Encode 分类变量并同时缩放连续变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很困惑,因为如果您先执行 OneHotEncoder
然后执行 StandardScaler
会出现问题,因为缩放器还会缩放先前由 转换的列OneHotEncoder
.有没有办法同时执行编码和缩放,然后将结果连接在一起?
I'm confused because it's going to be a problem if you first do OneHotEncoder
and then StandardScaler
because the scaler will also scale the columns previously transformed by OneHotEncoder
. Is there a way to perform encoding and scaling at the same time and then concatenate the results together?
推荐答案
当然可以.只需根据需要单独缩放和单热编码单独的列:
Sure thing. Just separately scale and one-hot-encode the separate columns as needed:
# Import libraries and download example data
from sklearn.preprocessing import StandardScaler, OneHotEncoder
dataset = pd.read_csv("https://stats.idre.ucla.edu/stat/data/binary.csv")
print(dataset.head(5))
# Define which columns should be encoded vs scaled
columns_to_encode = ['rank']
columns_to_scale = ['gre', 'gpa']
# Instantiate encoder/scaler
scaler = StandardScaler()
ohe = OneHotEncoder(sparse=False)
# Scale and Encode Separate Columns
scaled_columns = scaler.fit_transform(dataset[columns_to_scale])
encoded_columns = ohe.fit_transform(dataset[columns_to_encode])
# Concatenate (Column-Bind) Processed Columns Back Together
processed_data = np.concatenate([scaled_columns, encoded_columns], axis=1)
这篇关于One-Hot-Encode 分类变量并同时缩放连续变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文