Pandas 一种热门编码:将频率较低的类别捆绑在一起

anw*_*ian 5 python pandas scikit-learn one-hot-encoding

我正在对具有大约 18 个不同类型值的分类列进行一种热编码。我只想为那些出现超过某个阈值(假设为 1%)的值创建新列,并创建另一个名为other values1 如果值不是那些频繁值的列。

我在 Sci-kit 学习中使用 Pandas。我已经探索了 pandasget_dummies和 sci-kit learn's one hot encoder,但无法弄清楚如何将频率较低的值捆绑到一列中。

piR*_*red 4

计划

  • pd.get_dummies正常情况下对一个热编码
  • sum() < threshold识别聚合的列
    • pd.value_counts与参数一起使用normalize=True来获取出现的百分比。
  • join

def hot_mess2(s, thresh):
    d = pd.get_dummies(s)
    f = pd.value_counts(s, sort=False, normalize=True) < thresh
    if f.sum() == 0:
        return d
    else:
        return d.loc[:, ~f].join(d.loc[:, f].sum(1).rename('other'))
Run Code Online (Sandbox Code Playgroud)

考虑pd.Series s

s = pd.Series(np.repeat(list('abcdef'), range(1, 7)))

s

0     a
1     b
2     b
3     c
4     c
5     c
6     d
7     d
8     d
9     d
10    e
11    e
12    e
13    e
14    e
15    f
16    f
17    f
18    f
19    f
20    f
dtype: object
Run Code Online (Sandbox Code Playgroud)

hot_mess(s, 0)

    a  b  c  d  e  f
0   1  0  0  0  0  0
1   0  1  0  0  0  0
2   0  1  0  0  0  0
3   0  0  1  0  0  0
4   0  0  1  0  0  0
5   0  0  1  0  0  0
6   0  0  0  1  0  0
7   0  0  0  1  0  0
8   0  0  0  1  0  0
9   0  0  0  1  0  0
10  0  0  0  0  1  0
11  0  0  0  0  1  0
12  0  0  0  0  1  0
13  0  0  0  0  1  0
14  0  0  0  0  1  0
15  0  0  0  0  0  1
16  0  0  0  0  0  1
17  0  0  0  0  0  1
18  0  0  0  0  0  1
19  0  0  0  0  0  1
20  0  0  0  0  0  1
Run Code Online (Sandbox Code Playgroud)

hot_mess(s, .1)

    c  d  e  f  other
0   0  0  0  0      1
1   0  0  0  0      1
2   0  0  0  0      1
3   1  0  0  0      0
4   1  0  0  0      0
5   1  0  0  0      0
6   0  1  0  0      0
7   0  1  0  0      0
8   0  1  0  0      0
9   0  1  0  0      0
10  0  0  1  0      0
11  0  0  1  0      0
12  0  0  1  0      0
13  0  0  1  0      0
14  0  0  1  0      0
15  0  0  0  1      0
16  0  0  0  1      0
17  0  0  0  1      0
18  0  0  0  1      0
19  0  0  0  1      0
20  0  0  0  1      0
Run Code Online (Sandbox Code Playgroud)