Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace entire string occurrences, not substrings, in a Polars DataFrame?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"))

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading