Pandas:用唯一值替换多个列值

时间:2017-11-14 13:33:29

标签: python pandas replace

我有一个带有许多“对象”列的pandas DataFrame,其中每个列都包含许多值(模态)。然后,我希望每列只保留 10种最常用的模式,其他的替换为'Oth'。

例如,如果我有一个包含4个不同值的列'obj_col1':

obj_col1
'A'
'A'
'B'
'C'
'B'
'D'

我希望保持最频繁的2,在这里'A'和'B',并将其余部分替换为'Oth':

obj_col2
'A'
'A'
'B'
'Oth'
'B'
'Oth'

一个对象列(分类变量)的代码是:

# sorted list of modalities of 'categ_var' 
list_freq_modal = df['categ_var'].value_counts().index.tolist()
# replace all the modalities except the first 10 by 'Oth'
df['categ_var'].replace(list_freq_modal[10:],'Oth', inplace=True)

但我有一个错误:'NoneType'对象没有属性'any'

您是否有任何想法以更优化的方式实施它?

1 个答案:

答案 0 :(得分:2)

我们可以通过映射value_counts并使用value_counts.head(2)获取掩码,而不是替换,我们可以使用wherenotnull(),即

x = df['obj_col1'].value_counts().head(2)
#B    2
#A    2
#Name: obj_col1, dtype: int64

df['obj_col1'].where(df['obj_col1'].map(x).notnull(),'Oth')

输出:

0      A
1      A
2      B
3    Oth
4      B
5    Oth
Name: obj_col1, dtype: object
df['obj_col1'].map(x).notnull() # This will give the mask. 
0     True
1     True
2     True
3    False
4     True
5    False
Name: obj_col1, dtype: bool
相关问题