带有字符串分类值的 OneHotEncoder [英] OneHotEncoder with string categorical values

查看:41
本文介绍了带有字符串分类值的 OneHotEncoder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 numpy 矩阵:

I have the following numpy matrix:

M = [
    ['a', 5, 0.2, ''],
    ['a', 2, 1.3, 'as'],
    ['b', 1, 2.3, 'as'],
]
M = np.array(M)

我想对分类值进行编码('a'、'b'、''、'as').我尝试使用 OneHotEncoder 对其进行编码.问题是它不适用于字符串变量并产生错误.

I would like to encode categorical values ('a', 'b', '', 'as'). I tried to encode it using OneHotEncoder. The problem is that is does not work with string variables and generates the error.

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

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

I know that I have to use categorical_features to show which values I am going to encode and I thought that by providing dtype I will be able to handle string values, but I can not. So is there a way to encode categorical values in my matrix?

推荐答案

您可以使用 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_ 保存与列的对应关系:

dv.feature_names_ holds correspondence to the columns:

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

这篇关于带有字符串分类值的 OneHotEncoder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆