gpt4 book ai didi

python - 在 Dataframe 的句子中查找多个单词并转换为分数的总和

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

我有以下数据框:

    Sentence
0 Cat is a big lion
1 Dogs are descendants of wolf
2 Elephants are pachyderm
3 Pachyderm animals include rhino, Elephants and hippopotamus

我需要创建一个 python 代码,它查看上面句子中的单词,并根据以下不同的数据框计算每个单词的分数总和。

Name          Score
cat 1
dog 2
wolf 2
lion 3
elephants 5
rhino 4
hippopotamus 5

例如,对于第 0 行,分数将为 1(猫)+ 3(狮子)= 4

我希望创建如下所示的输出。

    Sentence                                                      Value
0 Cat is a big lion 4
1 Dogs are descendants of wolf 4
2 Elephants are pachyderm 5
3 Pachyderm animals include rhino, Elephants and hippopotamus 14

最佳答案

作为第一步,您可以尝试 splitmap基于的方法,然后使用 groupby 计算分数.

v = df1['Sentence'].str.split(r'[\s.!?,]+', expand=True).stack().str.lower()
df1['Value'] = (
v.map(df2.set_index('Name')['Score'])
.sum(level=0)
.fillna(0, downcast='infer'))

df1
Sentence Value
0 Cat is a big lion 4
1 Dogs are descendants of wolf 4 # s/dog/dogs in df2
2 Elephants are pachyderm 5
3 Pachyderm animals include rhino, Elephants and... 14

关于python - 在 Dataframe 的句子中查找多个单词并转换为分数的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52264354/

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