在python中执行OneHotEncoder后,保留列名的最佳方法是什么?
在python中执行一个热编码器之后,保留列名的最佳方法是什么?我的所有功能都是分类的,因此我喜欢以下内容: 因此,导入数据集后,它如下所示在python中执行OneHotEncoder后,保留列名的最佳方法是什么?,python,machine-learning,one-hot-encoding,pyspider,Python,Machine Learning,One Hot Encoding,Pyspider,在python中执行一个热编码器之后,保留列名的最佳方法是什么?我的所有功能都是分类的,因此我喜欢以下内容: 因此,导入数据集后,它如下所示 PlaceID Date ... BlockedRet OverallSeverity 0 23620 1/10/2019 ... 1 1 1 13352 1/10/2019 ... 1 1 2 13674 1
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
'''
参考:
方法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
'''
参考:
对不起,但我不清楚您在问什么:1)加载数据后,您的数据帧
df
看起来像什么?请在问题中加上一个例子;2) df.iloc[:,+2:-1]
应该如何执行一个热编码?在我看来,这就像是选择了第三列;3) 最后你想得到什么?请在问题中分享一个你想要的输出的例子。希望问题现在清楚了,非常感谢!欢迎:)……一旦你有足够的声誉,请立即投票并接受答案。