为了账号安全,请及时绑定邮箱和手机立即绑定

将字典的值与数据帧的两列的值进行匹配,并用字典的键替换第三列的值

将字典的值与数据帧的两列的值进行匹配,并用字典的键替换第三列的值

呼啦一阵风 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 关注
  • 1591 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信