python - 将 dict 的值与数据帧的两列的值匹配,并将第三列的值替换为 dict 的键
问题描述
我有一个像这样的熊猫数据框:
Index | Line Item | Insertion Order | Creative Type
_________________________________________________________________________________________________
1 | blbl 33 dEs '300x600' Q3 | hello 444 | UNKNOWN
2 | QQQ4 Hello trueview Apple | something 68793274 | UNKNOWN
3 | A useless string | pre-roll Video <10 tttt 89 CASIO | UNKNOWN
4 | 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 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
最简单的方法是什么?(如果可能的话,计算成本更低)
解决方案
通过反转给定的键值对来创建替换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
推荐阅读
- objective-c - iOS 14 AVPlayer 不显示视频,但播放声音
- javascript - React 组件的实例
- unity3d - Turtlebot 在 Unity3D 上使用 Ros# 疯狂地旋转和摇摆
- r - 如何在另一个包中使用 R 包中的“未导出”数据集
- python - 尝试在 Python 中生成一个 128 x 128px 的正方形
- python - 根据子条件过滤 Panda DataFrame 父行
- networking - 当两者都连接到同一个热点时,客户端无法访问服务器上托管的网站
- python - 我如何提示用户将值输入到字典键中:姓名、年龄、课程并使用 python 以表格形式打印值
- bootstrap-4 - Bootstrap 4表格单元格垂直对齐似乎不像文档建议的那样工作
- javascript - 如何使用追加停止 JavaScript for 循环