1

I have a dataframe and alot of the values in one of the columns have python-unfriendly characters, like &.

I wanted to make a dictionary and then loop through with find and replacements

sort of like this:

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

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

however this brings up the following error code:

error: nothing to repeat at position 0

1 Answer 1

2

I think you need escape special regex characters in dictionary comprehension:

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks - that worked perfectly. I'll accept answer once the timer lets me. Thanks alot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.