gpt4 book ai didi

Python:结合低频因素/类别计数

转载 作者:行者123 更新时间:2023-11-28 19:42:27 25 4
gpt4 key购买 nike

有一个很棒的solution in R .

我的 df.column 看起来像:

Windows
Windows
Mac
Mac
Mac
Linux
Windows
...

我想在此 df.column 向量中用“其他”替换低频类别。例如,我需要我的 df.column 看起来像

Windows
Windows
Mac
Mac
Mac
Linux -> Other
Windows
...

我想重命名这些稀有类别,以减少回归中的因素数量。这就是为什么我需要原始向量。在 python 中,运行命令获取频率表后,我得到:

pd.value_counts(df.column)


Windows 26083
iOS 19711
Android 13077
Macintosh 5799
Chrome OS 347
Linux 285
Windows Phone 167
(not set) 22
BlackBerry 11

我想知道是否有一种方法可以将“Chrome OS”、“Linux”(低频数据)重命名为另一个类别(例如类别“其他”),并且以一种有效的方式进行。

最佳答案

通过查找占用百分比来掩码,即:

series = pd.value_counts(df.column)
mask = (series/series.sum() * 100).lt(1)
# To replace df['column'] use np.where I.e
df['column'] = np.where(df['column'].isin(series[mask].index),'Other',df['column'])

用 sum 改变索引:

new = series[~mask]
new['Other'] = series[mask].sum()

Windows 26083
iOS 19711
Android 13077
Macintosh 5799
Other 832
Name: 1, dtype: int64

如果你想替换索引那么:

series.index = np.where(series.index.isin(series[mask].index),'Other',series.index)

Windows 26083
iOS 19711
Android 13077
Macintosh 5799
Other 347
Other 285
Other 167
Other 22
Other 11
Name: 1, dtype: int64

解释

(series/series.sum() * 100) # This will give you the percentage i.e 

Windows 39.820158
iOS 30.092211
Android 19.964276
Macintosh 8.853165
Chrome OS 0.529755
Linux 0.435101
Windows Phone 0.254954
(not set) 0.033587
BlackBerry 0.016793
Name: 1, dtype: float64

.lt(1) 相当于小于 1。这会根据该掩码索引为您提供一个 bool 掩码并分配数据

关于Python:结合低频因素/类别计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47418299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com