【问题标题】:conditional replacement within strings of pandas dataframe column熊猫数据框列字符串中的条件替换
【发布时间】:2018-02-11 19:52:15
【问题描述】:

假设我的 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('.', '')

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

【问题讨论】:

    标签: python string pandas replace slice


    【解决方案1】:

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

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

    或借助 apply incase 寻找替代方案

    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 4ABCD 数据类型:对象

    【讨论】:

    • 很高兴帮助@MichielV。 .如果我的回答对您有帮助,请不要忘记接受 - 单击答案旁边的复选标记 (✓) 将其从灰色切换为已填充。学习愉快。
    【解决方案2】:

    您可以将 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
    >>> 
    

    【讨论】:

    • 非常感谢 MedAli,我现在可以继续我的项目了!
    【解决方案3】:

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

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

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

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

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

    【讨论】:

    • 感谢您的快速回复,这立即解决了我的问题!
    【解决方案4】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-07
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 2021-12-20
      • 2018-08-01
      • 1970-01-01
      相关资源
      最近更新 更多