我有一个数据帧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']]})
我还有一个数据框df2
,它包含单个单词字符串以及与每个单词相关的分数:
使用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]})
使用:
方法1
创建一个用于在apply中映射的基字典
方法2
创建一个新的序列来展开
^{pr2}$df1
中的单词,但保留索引值,以便我们可以使用count和sum进行聚合。在你能做到的
相关问题 更多 >
编程相关推荐