Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 具有要素名称的OneHot向量_Python_Pandas_Machine Learning_Scikit Learn - Fatal编程技术网

Python 具有要素名称的OneHot向量

Python 具有要素名称的OneHot向量,python,pandas,machine-learning,scikit-learn,Python,Pandas,Machine Learning,Scikit Learn,查看的文档中,似乎没有一种方法可以将特征名称作为OneHot向量的前缀。有人知道解决这个问题的方法吗?我错过什么了吗 示例数据帧: df = pd.DataFrame({'a':['c1', 'c1', 'c2', 'c1', 'c3'], 'b':['c1', 'c4', 'c1', 'c1', 'c1']}) from sklearn.preprocessing import OneHotEncoder onehot = OneHotEncoder() onehot.fit(df) o

查看的文档中,似乎没有一种方法可以将特征名称作为OneHot向量的前缀。有人知道解决这个问题的方法吗?我错过什么了吗

示例数据帧:

df = pd.DataFrame({'a':['c1', 'c1', 'c2', 'c1', 'c3'], 'b':['c1', 'c4', 'c1', 'c1', 'c1']})

from sklearn.preprocessing import OneHotEncoder

onehot = 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)

下面是您需要执行的操作,以包括来自的功能名称

输出:

array(['a_c1', 'a_c2', 'a_c3', 'b_c1', 'b_c4'], dtype=object)
每份文件:

获取功能名称(自我,输入功能=无)
返回输出要素的要素名称

参数:输入特征:字符串列表,长度n特征, 输入功能的可选字符串名称(如果可用)。默认情况下, 使用“x0”、“x1”、“xn_特征”

返回:输出\功能\名称:字符串数组,长度 n_输出功能


让我们创建一个包含3列的数据框架,每列都有一些分类值

import pandas as pd
from sklearn.preprocessing import OneHotEncoder

df_dict= {'Sex' :['m', 'f' ,'m' ,'f'] , 'City' : ['C1' , 'C2' , 'C3' , 'C4'] , 'States' :['S1' , 'S2', 'S3', 'S4']}
df = pd.DataFrame.from_dict(df_dict)
cat_enc = OneHotEncoder(handle_unknown = 'ignore')
transformed_array = cat_enc.fit_transform(df).toarray()
transformed_df = pd.DataFrame(transformed_array , columns= cat_enc.get_feature_names(df.columns))
transformed_df.head()
我们将得到以下输出-

City_C1 City_C2 City_C3 City_C4 Sex_f   Sex_m   States_S1   States_S2   States_S3   States_S4
0   1.0 0.0 0.0 0.0 0.0 1.0 1.0 0.0 0.0 0.0
1   0.0 1.0 0.0 0.0 1.0 0.0 0.0 1.0 0.0 0.0
2   0.0 0.0 1.0 0.0 0.0 1.0 0.0 0.0 1.0 0.0
3   0.0 0.0 0.0 1.0 1.0 0.0 0.0 0.0 0.0 1.0

啊,有办法!谢谢@scott:)正是因为这个原因,我在文档中更新了这个示例。查看文档的开发版本
City_C1 City_C2 City_C3 City_C4 Sex_f   Sex_m   States_S1   States_S2   States_S3   States_S4
0   1.0 0.0 0.0 0.0 0.0 1.0 1.0 0.0 0.0 0.0
1   0.0 1.0 0.0 0.0 1.0 0.0 0.0 1.0 0.0 0.0
2   0.0 0.0 1.0 0.0 0.0 1.0 0.0 0.0 1.0 0.0
3   0.0 0.0 0.0 1.0 1.0 0.0 0.0 0.0 0.0 1.0