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

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

將字典的值與數據幀的兩列的值進行匹配,并用字典的鍵替換第三列的值

將字典的值與數據幀的兩列的值進行匹配,并用字典的鍵替換第三列的值

呼啦一陣風 2023-08-22 15:59:12
我有一個像這樣的熊貓數據框:Index | Line Item                   |        Insertion Order                    | Creative Type_________________________________________________________________________________________________1     | blbl 33 dEs '300x600' Q3    | hello 444                                 | UNKNOWN2     | QQQ4 Hello trueview Apple   | something 68793274                        | UNKNOWN3     |   A useless  string         | pre-roll Video <10 tttt 89 CASIO          | UNKNOWN4     | Something not in dict       | Neither here                              | UNKNOWN還有這樣的字典: dct = {'RISING STARS': ['300x600', 'Box 300x600', '300x250', 'Box 300x250', 'Classic Skin', 'Main Banner', 'Half Banner', 'Masthead', 'Push Bar', 'Strip', 'In Image', 'Mix formati display rising'],'VIDEO': ['trueview', 'Video Banner', 'Video in Picture', 'Videobox', 'Mid-roll Video', 'Pre-roll+Inread', 'Pre-roll Video <10', 'Pre-roll Video =10', 'Pre-roll Video =15', 'Pre-roll Video =20', 'Pre-roll Video =30' ,'Pre-roll Video >30','Inread / Intext / Outstream','Mix formati video','Post-roll Video','Inread XXX (Landscape/Vertical/Square)', 'Pre-roll Video Sponsored Session' ,'Pre-roll Video Viewmax' ,'Pre-roll Video Takeover']}我想替換我的數據幀的創意類型列中的值:如果該列的值Line Item或Insertion Order與字典的值匹配,則該列的相應行Creative Type應采用字典鍵的名稱。如果沒有匹配,則列廣告素材類型的相應行應接收值NaN。預期輸出是:Index | Line Item                   |        Insertion Order                    | Creative Type_________________________________________________________________________________________________1     | blbl 33 dEs '300x600' Q3    | hello 444                                 | RISING STARS2     | QQQ4 Hello trueview Apple   | something 68793274                        | VIDEO3     |   A useless  string         | pre-roll Video <10 tttt 89 CASIO          | VIDEO4     | Something not in dict       | Neither here                              | NaN最簡單的方法是什么?(如果可能的話,計算成本更低)
查看完整描述

1 回答

?
萬千封印

TA貢獻1891條經驗 獲得超3個贊

通過反轉給定的鍵值對來創建替換dict字典,即對于列表中的每個值將其映射到其相應的鍵,然后使用Series.replace替換組合列中的字符串Line Item以及Insertion Order替換字典中的相應值(當存在時)匹配,最后mask是無法替換的字符串:

r = {rf'(?i).*?\b{z}\b.*':x for x, y in dct.items() for z in y}

s = df['Line Item'].add(':' + df['Insertion Order'])

df['Creative Type'] = s.replace(r, regex=True).mask(lambda x: x.eq(s))

? ? ? ? ? ? ? ? ? ?Line Item? ? ? ? ? ? ? ? ? ?Insertion Order Creative Type

1? ?blbl 33 dEs '300x600' Q3? ? ? ? ? ? ? ? ? ? ? ? ?hello 444? RISING STARS

2? QQQ4 Hello trueview Apple? ? ? ? ? ? ? ? something 68793274? ? ? ? ?VIDEO

3? ? ? ? ? A useless? string? pre-roll Video <10 tttt 89 CASIO? ? ? ? ?VIDEO

4? ? ? Something not in dict? ? ? ? ? ? ? ? ? ? ? Neither here? ? ? ? ? ?NaN


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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