我正在对一个pandas DataFrame应用LabelEncoder,df
Feat1 Feat2 Feat3 Feat4 Feat5 A A A A E B B C C E C D C C E D A C D E
我正在对这样的DataFrame应用标签编码器 –
from sklearn import preprocessingle = preprocessing.LabelEncoder()intIndexed = df.apply(le.fit_transform)
标签的映射方式如下
A = 0B = 1C = 2D = 3E = 0
我猜测E
没有被赋值为4
,因为它只出现在Feat 5
列中,而没有出现在其他列中。
我想让E
被赋值为4
,但我不知道如何在DataFrame中实现这一点。
回答:
您可以先fit
标签编码器,然后再transform
标签到其标准化编码,如下所示:
In [4]: from sklearn import preprocessing ...: import numpy as npIn [5]: le = preprocessing.LabelEncoder()In [6]: le.fit(np.unique(df.values))Out[6]: LabelEncoder()In [7]: list(le.classes_)Out[7]: ['A', 'B', 'C', 'D', 'E']In [8]: df.apply(le.transform)Out[8]: Feat1 Feat2 Feat3 Feat4 Feat50 0 0 0 0 41 1 1 2 2 42 2 3 2 2 43 3 0 2 3 4
默认指定标签的一种方法是:
In [9]: labels = ['A', 'B', 'C', 'D', 'E']In [10]: enc = le.fit(labels)In [11]: enc.classes_ # 按字母顺序排序标签Out[11]: array(['A', 'B', 'C', 'D', 'E'], dtype='<U1')In [12]: enc.transform('E')Out[12]: 4