Python 带有字符串分类值的OneHotEncoder
我有以下numpy矩阵: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() 我知道我必
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']