Skip to content
Advertisement

Replacing values using dictionary

What are the reasons why are regex replacment doesn’t work? I have tried ensuring no excess spaces.

df.column
0    Test_With_Him
1    And_another option with him
2    and_another reason with her

replacement = {'_':' ',Test With': 'test with', 'and another': 'And another& AND'}
df['column'] = df.column.replace('s+',' ' , regex=True).str.strip().replace(replacement, regex=True)

When I do df.loc[df['column']=="and another reason with her"] nothing has changed.

Advertisement

Answer

Please use df.replace(regex=dict)

df=pd.DataFrame({'test':["Test With Him","And Another option with him",'and another reason with her']})

replacement = {r'Test With': 'test with', r'And Another': 'And another& AND'}

df=df.replace(regex=replacement)

                        test
0                     test with Him
1  And another& AND option with him
2       and another reason with her
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement