這是我的數(shù)據(jù)框:df = pd.DataFrame({'col1': [1, 1, 1, 2, 2, 3, 4],
'col2': [1, 3, 2, 4, 6, 5, 7]})我嘗試根據(jù)值在數(shù)據(jù)集中出現(xiàn)的頻率來重新編碼,在這里我想將僅出現(xiàn)一次的每個(gè)值重新標(biāo)記為“其他”。這是所需的輸出:#desired"
col1": [1,1,1,2,2,"other", "other"]我嘗試了這個(gè)但沒有成功:df["recoded"] = np.where(df["col1"].value_counts() > 1, df["col1"], "other")我的想法是保存值計(jì)數(shù)并過濾它們,然后循環(huán)結(jié)果數(shù)組,但這似乎過于復(fù)雜。有沒有一種簡單的“pythonic/pandas”方法來實(shí)現(xiàn)這個(gè)?
1 回答

精慕HU
TA貢獻(xiàn)1845條經(jīng)驗(yàn) 獲得超8個(gè)贊
您很接近 - 需要Series.map
與原始系列相同長度的系列DataFrame
:
df["recoded"]?=?np.where(df["col1"].map(df["col1"].value_counts())?>?1,?df["col1"],?"other")
GroupBy.transform
或者通過以下方式與計(jì)數(shù)值一起使用GroupBy.size
:
df["recoded"]?=?np.where(df.groupby('col1')["col1"].transform('size')?>?1,? ?????????????????????????df["col1"],? ?????????????????????????"other")
如果需要檢查重復(fù)項(xiàng),請使用Series.duplicated
withkeep=False
來返回所有重復(fù)項(xiàng)的掩碼:
df["recoded"]?=?np.where(df["col1"].duplicated(keep=False),?df["col1"],?"other")
print (df)
0? ? ?1? ? ?1? ? ? ?1
1? ? ?1? ? ?3? ? ? ?1
2? ? ?1? ? ?2? ? ? ?1
3? ? ?2? ? ?4? ? ? ?2
4? ? ?2? ? ?6? ? ? ?2
5? ? ?3? ? ?5? ?other
6? ? ?4? ? ?7? ?other
添加回答
舉報(bào)
0/150
提交
取消