首页 > 解决方案 > 将数据框行中的单词与字典的键进行比较

问题描述

我有一个数据框:

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

标签: pythonpandasdataframedictionary

解决方案


我们可以使用字典中的键构造正则表达式模式,然后从每一行中提取该模式的所有出现,然后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

推荐阅读