python - 如何用字典中的数字替换熊猫列中句子中的所有单词,然后对它们求和?
问题描述
我有以下数据框
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
注意:如果在 dc 中未找到该词,则使用 0 值,否则建议使用,因为未提及
推荐阅读
- powershell - 如何使用 Powershell 使用 Google 安全浏览 API 查询多个 URL?
- c++ - 为什么 const std::vector 将 const 应用于包含的对象?
- assembly - Pin工具,静态ins地址(INS_Address(ins))和instrumented指令的地址(IARG_INST_PTR)不同
- haproxy - 基于 cookie 名称子串的后端路由
- mysql - SQL查询两列日期之间的日期
- python - 如何反向缩放整个数据框?
- excel - 如何在公式中创建对可变数量列范围的引用?
- node.js - 带有 CSS 和 JS 文件的文件未在服务器上提供并打印 ��U�v�8��+
- python - 在 Python3.8 中,无法在 if 语句中获取要检查的变量
- python - numpy中获得n对距离的最快方法