查看OneHotEncoder
的文档,似乎没有办法将特征名称作为OneHot向量的前缀包含进去。有人知道有什么解决方法吗?我是不是错过了什么?
样本数据框:
df = pd.DataFrame({'a':['c1', 'c1', 'c2', 'c1', 'c3'], 'b':['c1', 'c4', 'c1', 'c1', 'c1']})from sklearn.preprocessing import OneHotEncoderonehot = OneHotEncoder()onehot.fit(df)onehot.get_feature_names()array(['x0_c1', 'x0_c2', 'x0_c3', 'x1_c1', 'x1_c4'], dtype=object)
考虑到编码器接收的是一个数据框,我希望能够得到类似这样的结果:
array(['a_c1', 'a_c2', 'a_c3', 'b_c1', 'b_c4'], dtype=object)
回答:
这是您需要做的,以便在get_feature_name
中包含您的特征名称。
onehot.get_feature_names(input_features=df.columns)
输出:
array(['a_c1', 'a_c2', 'a_c3', 'b_c1', 'b_c4'], dtype=object)
根据文档:
get_feature_name(self, input_features=None)
返回输出特征的特征名称。参数:input_features : 长度为n_features的字符串列表,可选 如果有的话,输入特征的字符串名称。默认情况下,使用“x0”, “x1”, … “xn_features”。
返回:output_feature_names : 长度为n_output_features的字符串数组