![](/img/trans.png)
[英]Replace a word in a sentence with words from a list and copying the new sentences in a column
[英]how to replace all words from sentences from a pandas column with numbers from a dictionary and then sum them?
我有以下數據幀
import pandas as pd
df = pd.DataFrame({'col': ['bad good better three worst', 'awful best one']})
我有以下字典dc = dict({'bad':-1,'good':1,'better':2,'worst':-3,'awful':-5})
我想將col
所有單詞替換為與dc
該單詞對應的數字,然后對數字求和。
首先,我嘗試使用替換
def replace_words(s, words):
for k, v in words.items():
s = s.replace('^'k+'$', v, regex=True)
return s
df['col'] = df['col'].apply(lambda x: [replace_words(i, dc) for i in x.split(' ')])
但這不起作用。
有任何想法嗎 ?
這應該工作
df.col.apply(lambda x: sum([dc.get(i) if dc.get(i) else 0 for i in x.split()]))
產量
0 -1
1 -5
使用list comprehension和get
for lookup值,默認值為0
, sum
:
df['col'] = [sum(dc.get(x, 0) for x in i.split()) for i in df['col']]
print (df)
col
0 -1
1 -5
在dict in
測試值的另一個解決方案:
df['col'] = [sum(dc.get(x) for x in i.split() if x in dc) for i in df['col']]
細節 :
print ([list(dc.get(x, 0) for x in i.split()) for i in df['col']])
[[-1, 1, 2, 0, -3], [-5, 0, 0]]
您可以使用series.str.findall()
查找字符串中的所有匹配單詞,並使用get()
替換dict值的單詞列表:
df.col.str.findall('|'.join(dc.keys())).apply(lambda x: sum([dc.get(i,i) for i in x]))
0 -1
1 -5
細節:
df.col.str.findall('|'.join(dc.keys()))
0 [bad, good, better, worst]
1 [awful]
Name: col, dtype: object
df.col.str.findall('|'.join(dc.keys())).apply(lambda x: [dc.get(i,i) for i in x])
0 [-1, 1, 2, -3]
1 [-5]
Name: col, dtype: object
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.