繁体   English   中英

pandas dataframe列字符串中的条件替换

[英]conditional replacement within strings of pandas dataframe column

假设我在Pandas数据框中有一个看起来像这样的列:

s = pd.Series(["ab-cd.", "abc", "abc-def/", "ab.cde", "abcd-"])

我想将此列用于模糊匹配,因此我想删除字符('。','/','-'),但仅在每个字符串的末尾删除,因此它看起来像这样:

s = pd.Series(["ab-cd", "abc", "abc-def", "ab.cde", "abcd"])

到目前为止,我起初很容易,因此与其生成要删除的字符的列表,我只是针对不同的字符重复了命令,例如:

if s.str[-1] == '.':
  s.str[-1].replace('.', '')

但这只会产生错误。 如何获得想要的结果,即结尾处没有字符的字符串(字符串中其余部分的字符必须保留)?

用正则表达式替换将帮助您获得输出

s.replace(r'[./-]$','',regex=True)

或在申请的帮助下寻找替代方案

s.apply(lambda x :x[:-1] if x[-1] is '.' or '-' or '/' else x) 
0      ab-cd
1        abc
2    abc-def
3     ab.cde
4       abcd
dtype: object

您可以将str.replace与正则表达式一起使用:

>>> s = pd.Series(["ab-cd.", "abc", "abc-def/", "ab.cde", "abcd-"])
>>> s.str.replace("\.$|/$|\-$","")
0      ab-cd
1        abc
2    abc-def
3     ab.cde
4       abcd
dtype: object
>>> 

可以简化为:

>>> s.str.replace("[./-]$","")
0      ab-cd
1        abc
2    abc-def
3     ab.cde
4       abcd
dtype: object
>>> 

您可以将str.replace与正则表达式一起使用

s.str.replace(r'[./-]$','')

[./-]内替换要替换的任何字符。 $表示匹配项应位于字符串的末尾。

要替换“就地”,请使用Series.replace

s.replace(r'[./-]$','', inplace=True, regex=True)

我可以使用以下代码从pandas DataFrame的列的字符串末尾删除字符:

s.replace(r'[./-]$','',regex=True)

方括号([./-])中的所有条目表示要删除的字符,而$表示应从末尾删除它们

暂无
暂无

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

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