如何使用Pandas的endswith()方法移除字符串列末尾的指定字符?
问题解答
可以实现,你可以通过两种常用方案处理该需求,以下是可直接运行的代码示例:
首先构造你给出的示例DataFrame:
import pandas as pd df = pd.DataFrame({ 'Sentences': [ 'This is a sentence', 'This is a sentence.', 'This is also a sentence', 'This is also a sentence.' ] })
方案1:使用endswith()实现(符合你提问中的思路)
通过遍历判断每个字符串是否以.结尾,符合条件则切片去掉最后一位:
df['Sentences'] = df['Sentences'].apply(lambda x: x[:-1] if x.endswith('.') else x)
方案2:使用str.rstrip()实现(更简洁高效,优先推荐)
Pandas内置的字符串批量处理方法str.rstrip()专门用于移除字符串末尾的指定字符,不需要手动写判断逻辑:
df['Sentences'] = df['Sentences'].str.rstrip('.')
补充说明
如果存在多个连续末尾句号的场景(例如example..),rstrip('.')会一次性移除所有末尾的句号,而上述endswith()的方案默认只会移除最后1个,可根据实际需求选择。
处理完成后再用df.duplicated('Sentences')即可正确识别成对的重复值。
内容的提问来源于stack exchange,提问作者Ken Russel Sy
相关产品推荐
相关产品推荐

