我有以下數(shù)據(jù)框: Sentence0 Cat is a big lion1 Dogs are descendants of wolf2 Elephants are pachyderm3 Pachyderm animals include rhino, Elephants and hippopotamus我需要創(chuàng)建一個 python 代碼,它查看上面句子中的單詞,并根據(jù)以下不同的數(shù)據(jù)框計算每個單詞的總和。Name Scorecat 1dog 2wolf 2lion 3elephants 5rhino 4hippopotamus 5例如,對于第 0 行,分數(shù)將為 1(貓)+ 3(獅子)= 4我希望創(chuàng)建一個如下所示的輸出。 Sentence Value0 Cat is a big lion 41 Dogs are descendants of wolf 42 Elephants are pachyderm 53 Pachyderm animals include rhino, Elephants and hippopotamus 14
3 回答

小怪獸愛吃肉
TA貢獻1852條經(jīng)驗 獲得超1個贊
首先,您可以嘗試一種基于splitandmap的方法,然后使用 計算分數(shù)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
添加回答
舉報
0/150
提交
取消