如何对不同形状的列表数据进行标签编码

时间:2019-02-08 21:38:52

标签: python pandas numpy scikit-learn

我的熊猫系列看起来像这样,我想使用LabelEncoder但出现此错误

unhashable type: 'list'
6           [1]
7          [14]
8           [1]
9           [6]
10      [2, 14]
11          [2]
12         [14]

我尝试将列表转换为字符串,但是列表中项目的形状不同。这是我的代码。

df_ln['LN_USES'] = df_ln.groupby('CUST_NO')['LN_USE'].transform('unique')
df_ln['LN_USES'] = df_ln['LN_USES'].apply(np.ndarray.tolist)
encoder = LabelEncoder()
encoder.fit_transform(df_ln['LN_USES'])

我想要的结果:

6           1
7           2
8           1
9           3
10          4
11          5
12          2

1 个答案:

答案 0 :(得分:0)

一种方法是使用分隔符将列表中的所有元素连接起来,然后将其转换为字符串。然后应用编码器。

df_ln['LN_USES'] = df_ln['LN_USE'].apply(lambda x: '_'.join(map(str, x)))

#    CUST_NO   LN_USE LN_USES
# 0        6      [1]       1
# 1        7     [14]      14
# 2        8      [1]       1
# 3        9      [6]       6
# 4       10  [2, 14]    2_14
# 5       11      [2]       2
# 6       12     [14]      14


encoder.fit_transform(df_ln['LN_USES'])
# array([0, 1, 0, 4, 3, 2, 1], dtype=int64)