方法1:你可以在pandas数据框上使用
get_dummies。
范例1:
import pandas as pds = pd.Series(list('abca'))pd.get_dummies(s)Out[]: a b c0 1.0 0.0 0.01 0.0 1.0 0.02 0.0 0.0 1.03 1.0 0.0 0.0范例2:
下面将把给定的列转换为热点。使用前缀具有多个虚拟变量。
import pandas as pddf = pd.Dataframe({ 'A':['a','b','a'], 'B':['b','a','c'] })dfOut[]: A B0 a b1 b a2 a c# Get one hot encoding of columns Bone_hot = pd.get_dummies(df['B'])# Drop column B as it is now enpreddf = df.drop('B',axis = 1)# Join the enpred dfdf = df.join(one_hot)df Out[]: A a b c 0 a 0 1 0 1 b 1 0 0 2 a 0 0 1方法2:使用Scikit学习
给定具有三个特征和四个样本的数据集,我们让编码器找到每个特征的最大值,并将数据转换为二进制的一键编码。
>>> from sklearn.preprocessing import OneHotEnprer>>> enc = oneHotEnprer()>>> enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]]) oneHotEnprer(categorical_features='all', dtype=<class 'numpy.float64'>, handle_unknown='error', n_values='auto', sparse=True)>>> enc.n_values_array([2, 3, 4])>>> enc.feature_indices_array([0, 2, 5, 9], dtype=int32)>>> enc.transform([[0, 1, 1]]).toarray()array([[ 1., 0., 0., 1., 0., 0., 1., 0., 0.]])



