具有字符串分类值

时间:2015-10-08 06:54:33

标签: 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')进行编码。我尝试使用OneHotEncoder对其进行编码。问题是,它不适用于字符串变量并生成错误。

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

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

1 个答案:

答案 0 :(得分:17)

您可以使用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_names_与列相对应:

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

相关问题