Home:ALL Converter>Replacing strings with special characters in pandas dataframe

Replacing strings with special characters in pandas dataframe

Ask Time:2022-10-26T00:52:36         Author:newuser1628

Json Formatter

I'm looking to replace strings inside DataFrame columns, these strings contain special characters.

I tried the following, but nothing changed in the DataFrame:

data = {'col1': ["series ${z_mask0}", "series ${z_mask1}", "series ${z_mask2}"]}

df = pd.DataFrame(data)
print(df)

old_values = ["${z_mask0}", "${z_mask1}", "${z_mask2}"]

new_values = ["${z_00}", "${z_01}", "${z_02}"]

df = df.replace(old_values_sign, new_values_sign, regex=True)
print(df)

The intended output is: ['series ${z_00}', 'series ${z_01}', 'series ${z_02']

Author:newuser1628,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/74197645/replacing-strings-with-special-characters-in-pandas-dataframe
Carmoreno :

You need to escape the $ character using \\ in the old_values list:\nold_values = ["\\${z_mask0}", "\\${z_mask1}", "\\${z_mask2}"]\n\nThe above should be enough. Here is all the code:\nold_values = ["\\${z_mask0}", "\\${z_mask1}", "\\${z_mask2}"]\nnew_values = ["${z_00}", "${z_01}", "${z_02}"]\ndf = df.replace(old_values, new_values, regex=True)\nprint(df)\n\nOutput:\n col1\n0 series ${z_00}\n1 series ${z_01}\n2 series ${z_02}\n",
2022-10-25T17:06:12
yy