【发布时间】:2019-01-12 14:20:05
【问题描述】:
我有一个pandas.DataFrame,如下所示:
print(df)
level type
'xyz' 1
'abc' 2
'abc' 4
'abc' 3
'xyz' 3
'qwe' 2
'asd' 5
'poi' 1
我想用新值 others 替换 level 列中值计数小于 2 的所有值。
print(df['level'].value_counts())
abc 3
xyz 2
poi 1
qwe 1
asd 1
在上面的示例中,计数为 1 的类别即 qwe, asd, poi 应替换为 others
预期输出:
level type
0 xyz 1
1 abc 2
2 abc 4
3 abc 3
4 xyz 3
5 others 2
6 others 5
7 others 1
我尝试了什么
cats = []
x = dict(df['level'].value_counts())
for k,v in x.items():
if v > 1:
cats.append(k)
df['level'] = [j if j in cats else 'others' for i,j in df['level'].iteritems()]
上面的代码生成了预期的输出,但是速度太慢了。所以我在找 以获得更有效的解决方案。
【问题讨论】:
-
标记的副本应该可以解决这个问题。 This answer 已更新,向您展示如何隔离计数为 1 的类别。
标签: python python-3.x pandas