Pandas 如何更新计数大于 x 的值

Pandas how update values with counts greater x

我有一个 pandas 列,其中包含很多出现次数少于 5 次的字符串,我不会删除这些值,但是我确实想用一个名为 [=14= 的占位符字符串替换它们].执行此操作的最佳方法是什么?

df= pd.DataFrame(['a','a','b','c'],columns=["x"])
# get value counts and set pruned I want something that does as follows
df[df[count<2]] = "pruned"

我怀疑有一种更有效的方法可以做到这一点,但简单的方法是构建一个计数字典,然后在这些值低于计数阈值时进行修剪。考虑示例 df

df= pd.DataFrame([12,11,4,15,6,12,4,7],columns=['foo'])

    foo
0   12
1   11
2   4
3   15
4   6
5   12
6   4
7   7

# make a dict with counts
count_dict = {d:(df['foo']==d).sum() for d in df.foo.unique()}
# assign that dict to a column
df['bar'] = [count_dict[d] for d in df.foo]
# loc in the 'pruned' tag
df.loc[df.bar < 2, 'foo']='pruned'

Returns 根据需要:

    foo bar
0   12      2
1   pruned  1
2   4       2
3   pruned  1
4   pruned  1
5   12      2
6   4       2
7   pruned  1

(当然,如果需要,您可以将 2 更改为 5 并转储该 bar 列)。

更新

根据对就地版本的请求,这里有一个单行代码,无需分配另一列或直接创建该字典(感谢@TrigonaMinima 的 values_count() 提示):

df= pd.DataFrame([12,11,4,15,6,12,4,7],columns=['foo'])
print(df)
df.foo = df.foo.apply(lambda row: 'pruned' if (df.foo.value_counts() < 2)[row] else row)
print(df)

根据需要再次 returns:

   foo
0   12
1   11
2    4
3   15
4    6
5   12
6    4
7    7
      foo
0      12
1  pruned
2       4
3  pruned
4  pruned
5      12
6       4
7  pruned

这是我根据上面的答案最终使用的解决方案。

import pandas as pd
df= pd.DataFrame([12,11,4,15,6,12,4,7],columns=['foo'])
# make a dict with counts
count_dict = dict(df.foo.value_counts())
# assign that dict to a column
df['temp_count'] = [count_dict[d] for d in df.foo]
# loc in the 'pruned' tag
df.loc[df.temp_count < 2, 'foo']='pruned'
df = df.drop(["temp_count"], axis=1)