python - 将数据框行中的单词与字典的键进行比较
问题描述
我有一个数据框:
import pandas as pd
test_df = pd.DataFrame({
'_id': ['1a','2b','3c','4d'],
'column': ['und der in zu',
'Kompliziertereswort something',
'Lehrerin in zu [Buch]',
'Buch (Lehrerin) kompliziertereswort']})
和一本字典:
{'und': 20,
'der': 10,
'in': 40,
'zu': 10,
'Kompliziertereswort': 2,
'Buch': 5,
'Lehrerin': 5}
我想向数据框中添加一个新列,该列表示该行中单词的平均值。如果该词不在该词典中,则应该忽略它。
_id column score
1a und der in zu 20
2b Kompliziertereswort something 2
3c Lehrerin in zu [Buch] 15
4d Buch (Lehrerin) kompliziertereswort 5
我认为我做了一些非常愚蠢的事情,即:将数据框写为文本文件,读取每一行;我列出了字典中的所有键,然后使用正则表达式检查该行是否包含单词。它没有工作,可能是因为括号。
我还尝试拆分数据框行,但它只是将其拆分为单独的字母:
for index, values in test_df.iterrows():
pos = 1
for x in values[1]:
print(pos, x)
pos += 1
解决方案
我们可以使用字典中的键构造正则表达式模式,然后从每一行中提取该模式的所有出现,然后map
将字典中的分数提取d
到匹配的字符串mean
中,然后level=0
得到平均值
pat = fr"\b({'|'.join(d)})\b"
test_df['score'] = test_df['column'].str.extractall(pat)[0].map(d).mean(level=0)
结果
print(test_df)
_id column score
0 1a und der in zu 20.0
1 2b Kompliziertereswort something 2.0
2 3c Lehrerin in zu [Buch] 15.0
3 4d Buch (Lehrerin) kompliziertereswort 5.0
推荐阅读
- kubernetes - 挂载路径错误:不是目录:未知
- javascript - 如何使用 Vue 中的 post 方法将对象从一个端点发送到另一个端点?
- sql-server - 使用 Telegraf 和 Influx 监控 Azure SQL 数据库
- angular - 使用 ngx 数据表切换列
- java - 我怎样才能打破一个字符串
标记到地图集合中并为其分配布尔值(如果存在)? - php - Outlook 中的 IMAP_OPEN 无法使用 PHP
- python - 读取 csv 文件时 MS Databricks Spark 中绝对 URI 中的相对路径
- sapui5 - sap.tnt.NavigationListItem 的稳定 ID(id 与键)
- javascript - 对购物车部分中的产品列表做出反应
- postgresql - 在 postgreSQL 中将文本转换为时间戳