首页 > 解决方案 > 在熊猫中查找和替换子字符串的循环

问题描述

我有一个数据框,并且其中一列中的许多值都包含对 python 不友好的字符,例如 &。

我想制作一本字典,然后循环查找和替换

有点像这样:

replacements = {
    " ": ""
    ,"&": "and"
    ,"/":""
    ,"+":"plus"
    ,"(":""
    ,")":""
    }

df['VariableName']=df['VariableName'].replace(replacements,regex=True)

然而,这带来了以下错误代码:

error: nothing to repeat at position 0

标签: pythonpandas

解决方案


我认为您需要在字典理解中转义特殊的正则表达式字符:

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

推荐阅读