首页 > 解决方案 > 如何用字典中的数字替换熊猫列中句子中的所有单词,然后对它们求和?

问题描述

我有以下数据框

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(' ')])

但这不起作用。

有任何想法吗 ?

标签: pythonpython-3.xpandas

解决方案


这应该工作

df.col.apply(lambda x: sum([dc.get(i) if dc.get(i) else 0 for i in x.split()]))

输出

0   -1
1   -5


注意:如果在 dc 中未找到该词,则使用 0 值,否则建议使用,因为未提及


推荐阅读