简体   繁体   English

Python str 条也删除想要的字符

[英]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 ie capitals or no capitals and just leave the integer value behind.我在 dataframe 中有一个名为“Ring”的列,其中一些值只包含一个 integer,一些包含“RING 20”或“RING 30”等。我想去掉“RING”这个词或任何变体,即大写或没有大写并将 integer 值留在后面。

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.这些尝试成功地删除了不需要的字符串,但是,对于不包含文本字符串的行,它也会删除 integer 值并留下 NaN。

How do I get around this?我该如何解决这个问题?

Thanks for any help谢谢你的帮助

You can use .apply() on your dataframe column.您可以在 dataframe 列上使用.apply() 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.在你应用的function中你可以测试该值是否是一个字符串,然后你可以做足够的处理,否则,按原样返回。

df["RING"].apply( lambda x: x.strip('RING') if isinstance(x, str) else x )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM