【问题标题】:How can I do column wise counts and change value when the frequency is less than 3?当频率小于 3 时,如何按列计数并更改值?
【发布时间】:2026-01-28 13:00:01
【问题描述】:

我有一个包含很多行的日期框,其中包含一些低频值。我需要按列计数,然后在频率小于 3 时更改值。

DF-输入

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-输出

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

【问题讨论】:

  • 我认为 Ayhan 的原始解决方案不会针对这个问题处理原始数据框中的 NaN。我建议这不是骗局。

标签: python pandas replace


【解决方案1】:

您将wherevalue_counts 一起使用:

df.where(df.apply(lambda x: x.groupby(x).transform('count')>2), 'Other')

输出:

       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:

d = df.apply(lambda x: x.groupby(x).transform('count'))
df.where(d.gt(2.0).where(d.notnull()).astype(bool), 'Other')

输出:

       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

【讨论】:

  • 好一个!我需要记住 df.where :)
  • 这不是你所需要的,这是!= idmax() 的任何地方,但它应该适用于那些小于 3 的人......
  • 是的,我用 df.mask 不够好!
  • @juanpa.arrivillaga 你是对的。我已经固定频率小于 3
  • 如何指定具体的列?
最近更新 更多