标签编码时保留顺序

时间:2019-07-16 23:22:03

标签: pandas scikit-learn data-science

当标签编码数字时

[1, 1, 2, 6]

LabelEncoder返回[0,0,1,2],因为它对类进行了排序

通过保留原始订单来获得[1,1,0,2]的最佳方法是什么

尝试-CategoricalIndex,其工作方式相同

from sklearn import preprocessing
le = preprocessing.LabelEncoder()
le.fit([2, 1, 2, 6])

# le.classes_ [1,2,6]

le.transform([1, 1, 2, 6]) 

3 个答案:

答案 0 :(得分:1)

我们可以使用factorize

pd.factorize([2, 1, 2, 6])[0]
array([0, 1, 0, 2])

答案 1 :(得分:0)

这是一种实现方法。想知道熊猫中是否有任何现有功能可以做到这一点。

refdict=dict()
for i,j in data.Hash.items():
    if j in refdict:
        refdict[j].append(i)
    else:
        refdict[j]=[i]
for i in refdict:
    refdict[i]=min(refdict[i])
data.Hash.apply(lambda x:refdict[x])

答案 2 :(得分:0)

我已自定义LabelEncoder以使用唯一性而不进行排序。尝试my wrapper on LabelEncoder

>>> le = CustLabelEncoder(preserve_order=True)

>>> le.fit([2, 1, 2, 6])
>>> le.classes_
# array([2, 1, 6])

>>> le.transform([2, 1, 2, 6]) 
# array([0, 1, 0, 2])

>>> le.inverse_transform([0, 1, 0, 2])
# array([2, 1, 2, 6])
>>> le = CustLabelEncoder(preserve_order=False)

>>> le.fit([2, 1, 2, 6])
>>> le.classes_
# array([1, 2, 6])

>>> le.transform([2, 1, 2, 6]) 
# array([1, 0, 1, 2])

>>> le.inverse_transform([0, 1, 0, 2])
# array([1, 2, 1, 6])