[英]Pandas conditionally replace value if >1 unique values for other column
[英]Pandas: Replace multiple column values by unique value
我有一個帶有許多“對象”列的熊貓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'
您有任何想法以更優化的方式實施它嗎?
代替替換,我們可以使用value_counts.head(2)
, where
通過映射value_counts並使用notnull()
獲得掩碼,即
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.