【发布时间】:2021-11-14 20:24:12
【问题描述】:
以下是数据框、字典和代码的示例,但对于庞大的字典效率极低。数据框的一列包含句子。代码从句子中提取每个单词,检查它是否在字典中并为其赋值。计算值的平均值(每句或每行)并将其保存在额外的列中。
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}
pat = fr"\b({'|'.join(map(re.escape, 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
由于浏览字典比使用正则表达式更有效,我相信必须有一种方法使用将句子拆分为单词并检查它们是否在字典中并计算平均。我还将字典转换为数据框并使用了explode(),但同样没有效率。
【问题讨论】:
-
您是否尝试过分析您的代码?如果是,处理中最耗时的部分是什么?
标签: python pandas dictionary