python - 在熊猫中查找和替换子字符串的循环
问题描述
我有一个数据框,并且其中一列中的许多值都包含对 python 不友好的字符,例如 &。
我想制作一本字典,然后循环查找和替换
有点像这样:
replacements = {
" ": ""
,"&": "and"
,"/":""
,"+":"plus"
,"(":""
,")":""
}
df['VariableName']=df['VariableName'].replace(replacements,regex=True)
然而,这带来了以下错误代码:
error: nothing to repeat at position 0
解决方案
我认为您需要在字典理解中转义特殊的正则表达式字符:
import re
df = pd.DataFrame({'VariableName':['ss dd +','(aa)']})
replacements = {re.escape(k):v for k, v in replacements.items()}
df['VariableName']=df['VariableName'].replace(replacements,regex=True)
print (df)
VariableName
0 ssddplus
1 aa
推荐阅读
- node.js - 有没有可用于在 angular8 中集成 Amazon-chime-sdk-js 的步骤?
- json - 将 JSON 字符串序列化为 JSON 对象
- azure-devops - 如何在不使用 PATCH http 方法的情况下通过 API azure devops 更新现有的 wotkitem(功能)卡状态
- azure - 从 Azure 构建/发布管道访问 Azure Key Vault
- android - 如何在应用发明者平台中添加喷射器
- python - 在不损失精度的情况下将双精度从 C++ 转移到 python
- java - 出现错误原因:java.lang.ClassNotFoundException:org.springframework.core.ReactiveAdapterRegistry
- cgal - 使用 CGAL 时出错:“Alpha_shape_cell_base_3”类没有名为“hide_points”的成员
- javascript - Modernizr:如果不支持,则在后台删除带有 .webp 的元素
- c# - 添加格式为 00:00 的计时器?