我有一长串短语(200,000):
phrase_list = ['some word', 'another example', ...]
还有一个两列pandas数据框,第一列中有描述,第二列中有一些得分
Description Score
this sentence contains some word in it 6
some word is on my mind 3
repeat another example of me 2
this sentence has no matches 100
another 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循环更快.然而,根据我的测试,结果看似相似.我没有意识到更有效的解决方案而不会导致多处理.