【问题标题】:Remove string if not followed by another string如果后面没有另一个字符串,则删除字符串
【发布时间】:2021-11-17 00:46:44
【问题描述】:

我有一个数据框,我在其中进行了一些字符串替换,例如:

df1["Restriction"] = df1["Restriction"].str.replace("vs", "&")

结果如下:

Restriction
Montreal & Vancouver
Montreal & 

我想要做的是删除 & 如果它后面没有另一个字符串,那么它会导致以下结果:

Restriction
Montreal & Vancouver
Montreal 

我曾考虑将最后一个字符切片,但那样会切掉所有内容。任何建议表示赞赏。

谢谢!

【问题讨论】:

    标签: python pandas string dataframe


    【解决方案1】:

    如果您不希望 vs 成为部分单词的一部分,您可以使用带有交替和捕获组的正则表达式,并使用单词边界 \b 包围 vs

    在捕获组中,匹配 vs 直到字符串的末尾,否则匹配 vs 作为替代。如果捕获组 1 存在,则替换为空字符串,否则替换为 &

    import pandas as pd
    
    texts = [
        "Montreal vs Vancouver",
        "Montreal vs",
        "devs"
    ]
    
    df1 = pd.DataFrame(texts, columns=["Restriction"])
    
    df1['Restriction'] = df1['Restriction'].str.replace(
        r'(\s*\bvs\s*$)|\bvs\b',
        lambda m: '' if m.group(1) else '&'
    )
    
    print(df1)
    

    输出

                Restriction
    0  Montreal & Vancouver
    1              Montreal
    2                  devs
    

    【讨论】:

      【解决方案2】:

      你可以使用regular expression:

      df1["Restriction"] = df1["Restriction"].str.replace("&$","")
      

      【讨论】:

        【解决方案3】:

        使用rstrip:

        df1["Restriction"] = df1["Restriction"].str.replace("vs", "&").str.rstrip("& ")
        

        【讨论】:

        • 谢谢!!那行得通。也尝试了一种新方法。
        猜你喜欢
        • 2021-03-04
        • 1970-01-01
        • 2023-03-08
        • 1970-01-01
        • 2018-08-05
        • 1970-01-01
        • 2012-01-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多