Home > Blockchain >  Python str strip also remove wanted characters
Python str strip also remove wanted characters

Time:09-20

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.

How do I get around this?

Thanks for any help

CodePudding user response:

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 )
  • Related