如何检查由查找数据帧的字符串列表组成的数据帧并执行计算?

Ins*_*u Q 8 python lookup match dataframe pandas

我有一个df1包含标记化字符串行的数据框:

df1 = pd.DataFrame(data = {'tokens' : [['auditioned', 'lead', 'role', 'play', 
'play'], ['kittens', 'adopted', 'family'], ['peanut', 'butter', 'jelly', 
'sandwiches', 'favorite'], ['committee', 'decorated', 'gym'], ['surprise', 
'party', 'best', 'friends']]})
Run Code Online (Sandbox Code Playgroud)

我还有一个df2包含单字符串的数据框以及与每个单词相关的分数:

df2 = pd.DataFrame(data = {'word' : ['adopted', 'auditioned',
'favorite', 'gym', 'play', 'sandwiches'], 'score' : [1, 2, 3, 4, 5,
6]})
Run Code Online (Sandbox Code Playgroud)

使用哪种df2查找"表" 的最佳方法是什么,我也可以使用它来帮助执行计算?

对于每一行df1,我需要检查是否存在任何单词df2.如果是,则计算找到的单词数,并将结果存储在一个被调用的系列中word_count(如果特定单词出现多次df1,则计算每次出现次数).此外,当df1存在一个单词时,将该单词df2的分数与在所调用的系列中找到的任何其他单词相加total score.最终输出应如下所示df3:

df3 = pd.DataFrame(data = {'tokens' : [['auditioned', 'lead', 'role', 'play', 'play'], ['kittens', 'adopted', 'family'], ['peanut', 'butter', 'jelly', 'sandwiches', 'favorite'], ['committee', 'decorated', 'gym'], ['surprise', 'party', 'best', 'friends']], 'word_count' : [3, 1, 2, 1, 0], 'total_score' : [12, 1, 9, 4, None]})
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 4

使用:

d = df2.set_index('word')['score']

def f(x):
    y = [d.get(a) for a in x if a in d]
    return pd.Series([len(y), sum(y)], index=['word_count','total_score'])

df3[['word_count','total_score']] = df3['tokens'].apply(f)
print (df3)
                                          tokens  word_count  total_score
0           [auditioned, lead, role, play, play]           3           12
1                     [kittens, adopted, family]           1            1
2  [peanut, butter, jelly, sandwiches, favorite]           2            9
3                    [committee, decorated, gym]           1            4
4               [surprise, party, best, friends]           0            0
Run Code Online (Sandbox Code Playgroud)