I am working with a Polars DataFrame that contains thousands of string columns, and I am looking for a way to replace all instances of the string "0" with "-1" in the entire DataFrame.
Here is the code I have attempted:
df.with_columns(pl.all().str.replace("0", "-1", literal=True))
However, I encountered an issue with this approach. When a cell contains a string like "011212", the result becomes "-111212", which is not the desired outcome. My intention is to exclusively replace the entire string "0" with "-1" while leaving any strings containing the substring "0" unchanged.
Thank you very much for your help.
>Solution :
You can use regex to define the exact string you wish to replace –
df.with_columns(pl.all().str.replace(r"^0$", "-1"))