Python 如何创建;“其他”;在熊猫栏中分类有效吗?
我有一个Python 如何创建;“其他”;在熊猫栏中分类有效吗?,python,python-3.x,pandas,Python,Python 3.x,Pandas,我有一个pandas.DataFrame如下: print(df) level type 'xyz' 1 'abc' 2 'abc' 4 'abc' 3 'xyz' 3 'qwe' 2 'asd' 5 'poi' 1 我想用新值其他值替换级别列中值计数小于2的所有值 print(df['level'].value_counts()) abc 3 xyz 2 poi 1 qwe 1 asd 1
pandas.DataFrame
如下:
print(df)
level type
'xyz' 1
'abc' 2
'abc' 4
'abc' 3
'xyz' 3
'qwe' 2
'asd' 5
'poi' 1
我想用新值其他值
替换级别
列中值计数小于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()]
上面的代码生成了预期的输出,但速度太慢。所以我在找
用于更有效的解决方案。使用v
和过滤的索引值创建布尔掩码,并通过以下方式设置值:
详细信息:
print (v.index[v])
Index(['qwe', 'asd', 'poi'], dtype='object')
标记的副本应该可以解决这个问题。已更新,以显示如何隔离计数为1的类别。
print (v.index[v])
Index(['qwe', 'asd', 'poi'], dtype='object')