Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.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 带有字符串分类值的OneHotEncoder_Python_Scikit Learn - Fatal编程技术网

Python 带有字符串分类值的OneHotEncoder

Python 带有字符串分类值的OneHotEncoder,python,scikit-learn,Python,Scikit Learn,我有以下numpy矩阵: M = [ ['a', 5, 0.2, ''], ['a', 2, 1.3, 'as'], ['b', 1, 2.3, 'as'], ] M = np.array(M) 我想对分类值进行编码('a','b','as')。我试着用计算机对它进行编码。问题是is不能处理字符串变量并生成错误 enc = preprocessing.OneHotEncoder() enc.fit(M) enc.transform(M).toarray() 我知道我必

我有以下numpy矩阵:

M = [
    ['a', 5, 0.2, ''],
    ['a', 2, 1.3, 'as'],
    ['b', 1, 2.3, 'as'],
]
M = np.array(M)
我想对分类值进行编码(
'a','b','as'
)。我试着用计算机对它进行编码。问题是is不能处理字符串变量并生成错误

enc = preprocessing.OneHotEncoder()
enc.fit(M)
enc.transform(M).toarray()

我知道我必须使用
分类功能
来显示我要编码的值,我认为通过提供
dtype
我将能够处理字符串值,但我不能。那么,有没有一种方法可以在我的矩阵中对分类值进行编码?

您可以使用
DictVectorizer

from sklearn.feature_extraction import DictVectorizer
import pandas as pd

dv = DictVectorizer(sparse=False) 
df = pd.DataFrame(M).convert_objects(convert_numeric=True)
dv.fit_transform(df.to_dict(orient='records'))

array([[ 5. ,  0.2,  1. ,  0. ,  1. ,  0. ],
       [ 2. ,  1.3,  1. ,  0. ,  0. ,  1. ],
       [ 1. ,  2.3,  0. ,  1. ,  0. ,  1. ]])
dv.feature\u names\u
保存与列的对应关系:

[1,2,'0=a','0=b','3=','3=as']