【问题标题】:Equivalent of fct_lump in pandas相当于熊猫中的 fct_lump
【发布时间】:2020-07-20 13:15:55
【问题描述】:

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

【问题讨论】:

标签: python r pandas forcats


【解决方案1】:
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'

【讨论】:

  • 请在您的回答中添加一些描述,说明您的回答是做什么的以及 OP 代码的问题是什么。
【解决方案2】:

你也可以试试datar:

>>> from datar.all import factor, rep, LETTERS, c, fct_lump_n, fct_count
>>> 
>>> x = factor(rep(LETTERS[:9], times=c(40, 10, 5, 27, 1, 1, 1, 1, 1)))
>>> x >> fct_count()
           f       n
  <category> <int64>
0          A      40
1          B      10
2          C       5
3          D      27
4          E       1
5          F       1
6          G       1
7          H       1
8          I       1
>>> x >> fct_lump_n(3) >> fct_count()
           f       n
  <category> <int64>
0          A      40
1          B      10
2          D      27
3      Other      10

免责声明:我是datar 包的作者。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-02
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多