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

精慕HU
TA貢獻1845條經驗 獲得超8個贊
您很接近 - 需要Series.map
與原始系列相同長度的系列DataFrame
:
df["recoded"]?=?np.where(df["col1"].map(df["col1"].value_counts())?>?1,?df["col1"],?"other")
GroupBy.transform
或者通過以下方式與計數值一起使用GroupBy.size
:
df["recoded"]?=?np.where(df.groupby('col1')["col1"].transform('size')?>?1,? ?????????????????????????df["col1"],? ?????????????????????????"other")
如果需要檢查重復項,請使用Series.duplicated
withkeep=False
來返回所有重復項的掩碼:
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
添加回答
舉報
0/150
提交
取消