Python 查找并替换子字符串中的循环
我有一个数据框,其中一列中的很多值都有python不友好的字符,比如& 我想编一本字典,然后循环查找和替换 有点像这样:Python 查找并替换子字符串中的循环,python,pandas,Python,Pandas,我有一个数据框,其中一列中的很多值都有python不友好的字符,比如& 我想编一本字典,然后循环查找和替换 有点像这样: replacements = { " ": "" ,"&": "and" ,"/":"" ,"+":"plus" ,"(":"" ,")":"" } df['VariableName']=df['VariableName'].replace(replacements,regex=True) 但是,这会产生以下
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
谢谢-这很有效。一旦计时器允许,我就接受答案。非常感谢