如果描述包含列表中的短语,Python Pandas总结得分

如果描述包含列表中的短语,Python Pandas总结得分,第1张

概述我有一长串短语(200,000): phrase_list = ['some word', 'another example', ...] 还有一个两列pandas数据框,第一列中有描述,第二列中有一些得分 Description Scorethis sentence contains some word in it 我有一长串短语(200,000):

phrase_List = ['some word','another example',...]

还有一个两列pandas数据框,第一列中有描述,第二列中有一些得分

Description                                    scorethis sentence contains some word in it         6some word is on my mind                        3repeat another example of me                   2this sentence has no matches                   100another example with some word                 10

有300,000行.对于phrase_List中的每个短语,如果在每一行中找到该短语,我想获得总分.因此,对于“某些词”,得分将是6 3 10 = 19.对于“另一个例子”,得分将是2 10 = 12.

到目前为止我的代码工作但很慢:

phrase_score = []for phrase in phrase_List:    phrase_score.append([phrase,df['score'][df['description'].str.contains(phrase)].sum()])

我想将pandas数据帧与一列中的短语和第二列中的分数一起返回(如果我有列表列表,这部分是微不足道的).但是,我想要一种更快的方式来获取列表列表.

解决方法 您可以使用字典理解为短语列表中的每个短语生成分数.

对于每个短语,它会在包含该短语的数据框中创建这些行的掩码.掩码是df.Description.str.contains(短语).然后将这个蒙版应用于分数,这些分数又相加,实际上是df.score [mask] .sum().

df = pd.DataFrame({'Description': ['this sentence contains some word in it','some word on my mind','repeat another word on my mind','this sentence has no matches','another example with some word'],'score': [6,3,2,100,10]})phrase_List = ['some word','another example']scores = {phrase: df.score[df.Description.str.contains(phrase)].sum()           for phrase in phrase_List}>>> scores{'another example': 10,'some word': 19}

在更详细地重新阅读您的帖子后,我注意到您的方法的相似性.但是,我相信字典理解可能比for循环更快.然而,根据我的测试,结果看似相似.我没有意识到更有效的解决方案而不会导致多处理.

总结

以上是内存溢出为你收集整理的如果描述包含列表中的短语,Python Pandas总结得分全部内容,希望文章能够帮你解决如果描述包含列表中的短语,Python Pandas总结得分所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1197454.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存