Python 如何在scikit中的分类数据上使用一个热编码器?

Python 如何在scikit中的分类数据上使用一个热编码器?,python,machine-learning,scikit-learn,Python,Machine Learning,Scikit Learn,我有如下数组(实际上是一个Panda数据帧,它有一个类似数组的数据结构),类似于以下内容: [ ['M', 4, 15] ['M', 3, 7] ['F', 5, 9] ['I', 4, 15] ] def tokenize(data, col_of_category): str_to_int, int_to_str = {}, {} for row in data: cat = row[col_of_category]

我有如下数组(实际上是一个Panda数据帧,它有一个类似数组的数据结构),类似于以下内容:

[
   ['M', 4, 15]
   ['M', 3, 7]
   ['F', 5, 9]
   ['I', 4, 15]
]
def tokenize(data, col_of_category):
    str_to_int, int_to_str = {}, {}
    for row in data:
        cat = row[col_of_category]
        if cat in str_to_int.keys(): token = str_to_int[cat]
        else:
            token = len(str_to_int.keys())
            str_to_int[cat] = token
            int_to_str[token] = cat
        row[col_of_category] = token # assuming your rows are mutable
    return str_to_int, int_to_str
我希望对这些数据进行预处理,以便在线性回归中使用。 我相信这样做的方法是使用一个热编码器:

但是,这仅在类别为整数时有效

我相信您可以使用
听写向量器


但是,这似乎只适用于字典,而不适用于数组。

使用类似以下代码将类别映射到整数:

[
   ['M', 4, 15]
   ['M', 3, 7]
   ['F', 5, 9]
   ['I', 4, 15]
]
def tokenize(data, col_of_category):
    str_to_int, int_to_str = {}, {}
    for row in data:
        cat = row[col_of_category]
        if cat in str_to_int.keys(): token = str_to_int[cat]
        else:
            token = len(str_to_int.keys())
            str_to_int[cat] = token
            int_to_str[token] = cat
        row[col_of_category] = token # assuming your rows are mutable
    return str_to_int, int_to_str

然后,您可以使用返回的字典来管理将来的映射和取消映射。然后,您可以只使用
OneHotEncoder
。您的算法不关心是否涉及字符串。

假设您的数据帧
df
如下:

>>> df
  col1  col2  col3
0    M     4    15
1    M     3     7
2    F     5     9
3    I     4    15
要将
col1
转换为一个热编码向量,可以使用pandas
get_dummies
方法

>>> df = pd.get_dummies(df, columns=['col1'])
>>> df
   col2  col3  col1_F  col1_I  col1_M
0     4    15       0       0       1
1     3     7       0       0       1
2     5     9       1       0       0
3     4    15       0       1       0