gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 11:48:23 25 4
gpt4 key购买 nike

我有一长串(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 dataframe,其中一列是短语,第二列是分数(如果我有列表,这部分很简单)。但是,我想要一种更快的方法来获取列表列表。

最佳答案

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

对于每个短语,它会创建数据框中包含该短语的那些行的掩码。掩码是 df.Description.str.contains(phrase)。然后将此掩码应用于分数,这些分数依次求和,有效地 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 总结分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33794498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com