假设我的 Pandas Dataframe 中有一个列,如下所示:
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('.', '')
但这只会产生错误。如何获得我想要的结果,即末尾没有字符的字符串(需要保留字符串其余部分中的字符)?
最佳答案
用正则表达式替换将帮助您获得输出
s.replace(r'[./-]$','',regex=True)
或者在申请的帮助下寻找替代方案
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 4 abcd dtype: object
关于python - pandas 数据框列字符串内的条件替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46022417/