首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当频率小于3时,如何进行逐行计数和更改值?

当频率小于3时,如何进行逐行计数和更改值?
EN

Stack Overflow用户
提问于 2018-01-30 22:00:49
回答 1查看 74关注 0票数 3

我有一个有很多行和一些低频值的数据。我需要进行逐行计数,然后更改频率小于3时的值。

DF-输入

代码语言:javascript
复制
Col1     Col2     Col3       Col4
 1        apple    tomato     apple
 1        apple    potato     nan
 1        apple    tomato     banana
 1        apple    tomato     banana
 1        apple    tomato     banana
 1        apple    tomato     banana
 1        grape    tomato     banana
 1        pear     tomato     banana
 1        lemon    tomato     burger

DF-输出

代码语言:javascript
复制
Col1     Col2     Col3       Col4
 1        apple    tomato     Other
 1        apple    Other      nan
 1        apple    tomato     banana
 1        apple    tomato     banana
 1        apple    tomato     banana
 1        apple    tomato     banana
 1        Other    tomato     banana
 1        Other    tomato     banana
 1        Other    tomato     Other
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-30 22:10:41

wherevalue_counts结合使用

代码语言:javascript
复制
df.where(df.apply(lambda x: x.groupby(x).transform('count')>2), 'Other')

输出:

代码语言:javascript
复制
       Col2    Col3    Col4
Col1                       
1     apple  tomato   Other
1     apple   Other  banana
1     apple  tomato  banana
1     apple  tomato  banana
1     apple  tomato  banana
1     apple  tomato  banana
1     Other  tomato  banana
1     Other  tomato  banana
1     Other  tomato   Other

更新:处理原始数据文件中的NaN:

代码语言:javascript
复制
d = df.apply(lambda x: x.groupby(x).transform('count'))
df.where(d.gt(2.0).where(d.notnull()).astype(bool), 'Other')

输出:

代码语言:javascript
复制
       Col2    Col3    Col4
Col1                       
1     apple  tomato   Other
1     apple   Other     NaN
1     apple  tomato  banana
1     apple  tomato  banana
1     apple  tomato  banana
1     apple  tomato  banana
1     Other  tomato  banana
1     Other  tomato  banana
1     Other  tomato   Other
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48531236

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档