亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Pandas - 根據 value_counts() 結果重新編碼變量

Pandas - 根據 value_counts() 結果重新編碼變量

眼眸繁星 2023-08-08 16:16:21
這是我的數據框: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.duplicatedwithkeep=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


查看完整回答
反對 回復 2023-08-08
  • 1 回答
  • 0 關注
  • 132 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號