Python 3.x 根据要删除的字符串列表删除字符串末尾的子字符串

Python 3.x 根据要删除的字符串列表删除字符串末尾的子字符串,python-3.x,pandas,substring,Python 3.x,Pandas,Substring,我有一个字符串列表 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'] 您的建议是什么?与re

我有一个字符串列表

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']
您的建议是什么?

与regex模式一起使用-为字符串的匹配结尾添加了
$
,为之前的匹配空格添加了
\s+
,并为regex
加入了

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

这个解决方案会奏效

    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, " ")

不测试您的解决方案中字符串的结尾我假设列表中的名称周围没有空格。请回答第二个问题,如果我的字符串列表中有多个单词,例如x=['llc sa'、'corp cor'、'sa se'],我希望在整个字符串中查找这些单词,而不仅仅是在末尾,我该怎么做?@Hector Simon Benavides然后使用
pat='|'.join(r“\b{}\b).在x中为y设置格式(y)df['Names']=df['Names'].str.replace('+pat+'),'').str replace('+','')
,未测试,仅在手机上使用。