python - 创建使用另一列中的字符串映射字典的数据框
问题描述
使用字典(下面的示例),需要创建一个新的数据框列,该列将示例数据框中的不同列,并且字符串中的第一个单词与字典键匹配,将值分配给新列。下面的例子:
dictionary = {'dog':'yellow', 'cat':'black, 'frog':'green', 'horse':'brown'}
原DF:
ColA:
The dog and horse ate food
Where is the frog?
horse and cat and frog walked together
所需的DF:
ColA: ColB
The dog and horse ate food yellow
Where is the frog? green
horse and cat and frog walked together brown
有什么建议么?谢谢!
解决方案
尝试:
df["ColB"] = df["ColA"].str.split(expand=True).apply(lambda x: x.str.strip('.?,!":;').map(dictionary)).bfill(axis=1)[0]
ColA ColB
0 The dog and horse ate food yellow
1 Where is the frog? green
2 horse and cat and frog walked together brown
推荐阅读
- excel - 尝试将记录集分配给数组时出现错误“BOF 或 EOF 为真......”
- .net - 是否可以在应用程序启动时强制 Serilog.Sink.File 启动一个新的日志文件?
- sql - DBMail到Outlook的vb6 vs SQL脚本,出了什么问题?
- php - 使用嵌套 for 循环显示数据
- c# - 在新桌面中启动进程
- html - 如何让我的背景处于固定位置?
- php - Laravel 进程组件安全问题?
- python - 仅将 tf.nn.softmax() 应用于张量的正元素
- scala - Scala中子类的简单练习
- python - 使用 API 将 HTML 表单数据转换为 Flask 脚本