Skip to content
Advertisement

How to replace the ‘,’ between two numbers like X,X% into X.X% in all the dataframe python

I have a column in pandas data frame like below. Column name is ‘ingredients_text’ enter image description here

Now I want to replace all the values like 5,5% to 5.5% in this column in all the dataframe.

Advertisement

Answer

We can use str.replace here:

df["ingredients_text"] = df["ingredients_text"].str.replace(r'b(d+),(d+)%', r'1.2%')

The pattern b(d+),(d+)% matches in the first and second capture groups, respectively, the whole number and decimal component of the percentage. Then we replace with 1.2%, replacing the comma with dot.

Advertisement