我有一个字符串列表
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']
您有什么建议?
最佳答案
使用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
关于python-3.x - 根据要删除的字符串列表删除字符串末尾的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59843991/