One Hot 编码单列

One Hot Encoding a single column

我正尝试在 Iris 数据集中的目标列 ('Species') 上使用一个热编码器。

但我收到以下错误:

ValueError: Expected 2D array, got 1D array instead:

Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

Id SepalLengthCm SepalWidthCm PetalLengthCm PetalWidthCm    Species
0   1   5.1 3.5 1.4         0.2     Iris-setosa
1   2   4.9 3.0 1.4         0.2     Iris-setosa
2   3   4.7 3.2 1.3         0.2     Iris-setosa
3   4   4.6 3.1 1.5         0.2     Iris-setosa
4   5   5.0 3.6 1.4         0.2     Iris-setosa

我做了 google 这个问题,我发现大多数 scikit 学习估计器需要一个二维数组而不是一维数组。

同时,我还发现我们可以尝试传递带有索引的dataframe来对单列进行编码,但是没有用

onehotencoder = OneHotEncoder(categorical_features=[df.columns.tolist().index('pattern_id')
X = dataset.iloc[:,1:5].values
y = dataset.iloc[:, 5].values

from sklearn.preprocessing import LabelEncoder, OneHotEncoder

labelencoder= LabelEncoder()
y = labelencoder.fit_transform(y)


onehotencoder = OneHotEncoder(categorical_features=[0])
y = onehotencoder.fit_transform(y)

我正在尝试对单个分类列进行编码并拆分为多个列(编码通常的工作方式)

ValueError: Expected 2D array, got 1D array instead: Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

表示您需要将数组转换为向量。 您可以通过以下方式做到这一点:

from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
import pandas as pd
import numpy as np

# load iris dataset 
>>> iris = datasets.load_iris()
>>> iris = pd.DataFrame(data= np.c_[iris['data'], iris['target']], columns= iris['feature_names'] + ['target'])
>>> y = iris.target.values
>>> onehotencoder = OneHotEncoder(categories='auto')
>>> y = onehotencoder.fit_transform(y.reshape(-1,1))
# y - will be sparse matrix of type '<class 'numpy.float64'>
# if you want it to be a array you need to 
>>> print(y.toarray())
[[1. 0. 0.]
 [1. 0. 0.]
    . . . . 
 [0. 0. 1.]
 [0. 0. 1.]]

您也可以使用 get_dummies 函数 (docs)

>>> pd.get_dummies(iris.target).head()
   0.0  1.0  2.0
0    1    0    0
1    1    0    0
2    1    0    0
3    1    0    0
4    1    0    0

希望对您有所帮助!

对于你的情况,因为看起来你使用的是 kaggle 数据集,所以我会使用

import pandas as pd
pd.get_dummies(df.Species).head()

Out[158]: 
   Iris-setosa  Iris-versicolor  Iris-virginica
0            1                0               0
1            1                0               0
2            1                0               0
3            1                0               0
4            1                0               0

请注意,此处的默认值对所有 类(3 个物种)进行编码,其中通常只使用两个并将均值差异与基线组进行比较,(例如 R 中的默认值或通常在执行 regression/ANOVA 时可以使用 drop_first 参数来完成)。

我遇到过类似情况,发现以下方法有效:

在 fit 或 fit_transform 命令中使用两个方括号作为列名

one_hot_enc = OneHotEncoder()

arr =  one_hot_enc.fit_transform(data[['column']])
df = pd.DataFrame(arr)

fit_transform 给你一个数组,你可以将其转换为 pandas 数据帧。您可以将其附加到原始数据框或直接分配给现有列。