【问题标题】:Remove substring at the end of a string based on a list of strings to remove根据要删除的字符串列表删除字符串末尾的子字符串
【发布时间】:2023-04-09 07:09:01
【问题描述】:

我有一个字符串列表

x=['llc', 'corp', 'sa'] 

我需要在包含字符串的数据框中的列末尾进行过滤:

df = pd.DataFrame(['Geeks corp', 'toto', 'tete coope', 'tete sa', 'tata corp', 'titi', 'tmtm'] , columns =['Names']) 

作为我想要的输出。有:

list = ['Geeks', 'toto', 'tete coope', 'tete', 'tata', 'titi', 'tmtm']

你有什么建议?

【问题讨论】:

    标签: python-3.x pandas substring


    【解决方案1】:

    Series.str.replace 与正则表达式模式一起使用 - 添加$ 以匹配字符串结尾,添加\s+ 以用于匹配空间之前并加入| 以用于正则表达式or

    pat = '|'.join(f'\s+{y}$' for y in x)
    df['Names'] = df['Names'].str.replace(pat, '')
    print (df)
            Names
    0       Geeks
    1        toto
    2  tete coope
    3        tete
    4        tata
    5        titi
    6        tmtm
    

    【讨论】:

    • 第二个问题,如果在我的字符串列表中我有多个单词,例如 x=['llc sa', 'corp cor', 'sa se'],我会喜欢在整个字符串中查看这些单词,而不仅仅是在末尾,我该怎么办?
    • @Hector Simon Benavides 然后使用pat = '|'.join(r"\b{}\b".format(y) for y in x) df['Names'] = df['Names'].str.replace('('+ pat + ')', '').str.replace(' +', ' '),未经测试,仅在手机上使用。
    【解决方案2】:

    这个解决方案会起作用

        import pandas as pd
        x=['llc', 'corp', 'sa'] 
        df = pd.DataFrame(['Geeks corp', 'toto', 'tete coope', 'tete sa', 'tata corp', 'titi', 'tmtm'] , columns =['Names'])
        for i in x:
            df["Names"] = df["Names"].str.replace(i, " ")
    

    【讨论】:

    • 未在您的解决方案中测试字符串结尾
    • 我假设列表中的名字周围没有空格。
    猜你喜欢
    • 1970-01-01
    • 2010-11-05
    • 1970-01-01
    • 1970-01-01
    • 2011-03-07
    • 2015-02-02
    相关资源
    最近更新 更多