如何在 python 中执行一次热编码

How to perform one hot encoding in python

您好,过去几个小时我一直在尝试这样做,但我似乎无法让它工作。我已经导入了必要的包并将我的 csv 文件分配给变量 X。

我的 csv 文件是一列,每个元素的数字范围从 0 到 9。我想创建另一个包含 0 和 1 的 10 列的 csv 文件以用作目标集。我试过使用 sklearns labelencoder 和 onehotencoder 但我没有任何运气。

感谢阅读并提前提供帮助。

如果是csv文件,可以通过以下方式使用Pandas包

import pandas as pd            #importing the package        
df = pd.read_csv(path)         #df is a variable containing the data-frame of the csv file
ydf = pd.get_dummies(df['label']) #'label' is the title of the the column
                                  #in the csv you want to one hot encode

勾选 pandas dummy documentation

如果是numpy数组可以试试下面的方法

import numpy as np
vector = np.arange(5)    # vector = [0 1 2 3 4]

one_hot = (vector == 0).astype(np.int)  #[1 0 0 0 0]
one_hot = (vector == 2).astype(np.int)  #[0 0 1 0 0]
one_hot = (vector == 4).astype(np.int)  #[0 0 0 0 1]

所以你可以用你的 numpy 数组来做到这一点

vector = np.arange(no_of_different_labels)

# transform labels into one hot representation
y_train_one_hot = (vector == y_train).astype(np.float)
# make sure you y_train is of size (m,1) and not (m,) for broadcasting to work

从这个 link

中得到