Pandas在value_counts()表格中减少了分类变量的数量

2024-10-02 14:28:08 发布

您现在位置:Python中文网/ 问答频道 /正文

熊猫新手,我想执行类似于Reduce number of levels for large categorical variables(分类变量的组合,以降低它们的级别) 下面的代码在R中可以正常工作

DTsetlvls <- function(x, newl)  
   setattr(x, "levels", c(setdiff(levels(x), newl), rep("other", length(newl))))

我的数据帧:

^{pr2}$

我手动创建一个聚合列,然后基于此,将频率较低的组(如“blue”标记为单个“other”组)。 但与简洁的R代码相比,这似乎有些笨拙。在这里正确的方法是什么?在


Tags: of代码numberreducefor分类variables级别
1条回答
网友
1楼 · 发布于 2024-10-02 14:28:08

我认为您可以将^{}^{}一起使用,其中条件与^{}一起使用:

df = pd.DataFrame({'Color':'Red Red Blue Red Violet Blue'.split(), 
                   'Value':[11,150,50,30,10,40]})
print (df)
    Color  Value
0     Red     11
1     Red    150
2    Blue     50
3     Red     30
4  Violet     10
5    Blue     40

a = df.Color.value_counts()
print (a)
Red       3
Blue      2
Violet    1
Name: Color, dtype: int64

#get top 2 values of index
vals = a[:2].index
print (vals)
Index(['Red', 'Blue'], dtype='object')

^{pr2}$

或者,如果需要替换所有非top值,请使用^{}

df['new1'] = df.Color.where(df.Color.isin(vals), 'other')
print (df)
    Color  Value   new1
0     Red     11    Red
1     Red    150    Red
2    Blue     50   Blue
3     Red     30    Red
4  Violet     10  other
5    Blue     40   Blue

相关问题 更多 >