python - 相当于熊猫中的 fct_lump
问题描述
Python 中是否有一个函数可以完成 R fct_lump 函数所做的事情(即将所有太小的组分组到一个“其他”组中)?
下面的例子:
library(dplyr)
library(forcats)
> x <- factor(rep(LETTERS[1:9], times = c(40, 10, 5, 27, 1, 1, 1, 1, 1)))
> x
[1] A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A B B B B B B B B
[49] B B C C C C C D D D D D D D D D D D D D D D D D D D D D D D D D D D E F G H I
Levels: A B C D E F G H I
> x %>% fct_lump_n(3)
[1] A A A A A A A A A A A A A A A A
[17] A A A A A A A A A A A A A A A A
[33] A A A A A A A A B B B B B B B B
[49] B B Other Other Other Other Other D D D D D D D D D
[65] D D D D D D D D D D D D D D D D
[81] D D Other Other Other Other Other
Levels: A B D Other
解决方案
pip install siuba
#( in python or anaconda prompth shell)
#use library as:
from siuba.dply.forcats import fct_lump, fct_reorder
#just like fct_lump of R :
df['Your_column'] = fct_lump(df['Your_column'], n= 10)
df['Your_column'].value_counts() # check your levels
#it reduces the level to 10, lumps all the others as 'Other'
推荐阅读
- typescript - 如何在树结构上列出 MongoDB 中的所有项目?
- typescript - 如何将参数添加到类的方法?
- python-3.x - 如何在python中输入由换行符分隔的整数列表
- javascript - ReactToPrint 忽略颜色变化,而是打印原始颜色
- typescript - 如何在 TypeScript 中使用 react-use-gesture 和 useSpring?
- embedded - stm32F1 DMA 在使用 2 个 UART 时冻结而没有任何错误
- laravel - 在 Laravel 中创建一个 cURL 请求类
- intel-fpga - Intel Cyclone LP 上的 CSI-2 接收器
- python - 并行化沿 xarray 数据集的维度工作的自定义函数
- javascript - 将 cookie 从不同域 example.co.uk 传递到 example.com