Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何创建;“其他”;在熊猫栏中分类有效吗?_Python_Python 3.x_Pandas - Fatal编程技术网

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')