来自OneHotEncoder的功能名称

时间:2019-02-07 10:13:00

标签: python-3.x scikit-learn one-hot-encoding

我正在使用OneHotEncoder编码一些分类变量(例如-Sex和AgeGroup)。编码器产生的特征名称类似-'x0_female','x0_male','x1_0.0','x1_15.0'等。

>>> train_X = pd.DataFrame({'Sex':['male', 'female']*3, 'AgeGroup':[0,15,30,45,60,75]})

>>> from sklearn.preprocessing import OneHotEncoder
>>> encoder = OneHotEncoder()
>>> train_X_encoded = encoder.fit_transform(train_X[['Sex', 'AgeGroup']])
>>> encoder.get_feature_names()
>>> array(['x0_female', 'x0_male', 'x1_0.0', 'x1_15.0', 'x1_30.0', 'x1_45.0',
       'x1_60.0', 'x1_75.0'], dtype=object)

是否有一种方法告诉OneHotEncoder以这样的方式创建要素名称,即在列开头添加列名称,例如-Sex_female,AgeGroup_15.0等,类似于熊猫{{1 }}。

3 个答案:

答案 0 :(得分:3)

您可以将具有原始列名的列表传递到get_feature_names

encoder.get_feature_names(['Sex', 'AgeGroup'])

将返回:

['Sex_female', 'Sex_male', 'AgeGroup_0', 'AgeGroup_15',
 'AgeGroup_30', 'AgeGroup_45', 'AgeGroup_60', 'AgeGroup_75']

答案 1 :(得分:1)

column_name = encoder.get_feature_names(['Sex', 'AgeGroup'])
one_hot_encoded_frame =  pd.DataFrame(train_X_encoded, columns= column_name)

答案 2 :(得分:1)

感谢您提供一个不错的解决方案。 @Nursnaaz 稀疏矩阵需要转换为密集矩阵。

column_name = encoder.get_feature_names(['Sex', 'AgeGroup'])
one_hot_encoded_frame =  pd.DataFrame(train_X_encoded.todense(), columns= column_name)
相关问题