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

Python str strip also remove wanted characters

I have a column in a dataframe called "Ring" some of the values contain just an integer and some contain "RING 20" or "RING 30" etc. I want to strip the word "RING" or any variation i.e capitals or no capitals and just leave the integer value behind.

I have tried the following, without success


DF['Ring'] = DF['Ring'].str.strip('RING')
DF['Ring'] = DF['Ring'].str.replace('[RING]')


These attempts successfully remove the unwanted string, however, for rows that do not contain a text string it also removes the integer value and leaves me with NaN.

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

How do I get around this?

Thanks for any help

>Solution :

You can use .apply() on your dataframe column. In the function you apply you can test if the value is a string, then you can do the adequate processing, otherwise, return it as is.

df["RING"].apply( lambda x: x.strip('RING') if isinstance(x, str) else x )
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