gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:11:37 31 4
gpt4 key购买 nike

在 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()

enter image description here结果没有原始列名,我如何使用相同的列名+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
'''

方法一:一个热编码器

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

关于python - 在 python 中执行 OneHotEncoder 后保留列名的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58816136/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com