如何用Python Pandas移除DataFrame列中字符串开头的冠词the、a、an
用Pandas移除字符串开头的冠词
直接用正则表达式配合str.replace就能精准匹配开头的冠词,不会影响字符串中间的内容。核心是利用正则的^锚定字符串开头,同时忽略大小写,匹配冠词后的空格。
具体实现代码
import pandas as pd # 示例DataFrame df = pd.DataFrame({ 'title': [ 'The Great Gatsby', 'a Tale of Two Cities', 'An apple a day', '1984', 'the cat and the dog' ] }) # 处理目标列:移除开头的the/a/an(忽略大小写),并去掉后面的空格 df['title_cleaned'] = df['title'].str.replace(r'^(?i)(the|a|an)\s+', '', regex=True) print(df)
代码解释
^:强制正则从字符串开头匹配,避免修改中间的冠词(?i):开启忽略大小写模式,同时匹配"The"/"the"、"A"/"a"、"An"/"an"(the|a|an):匹配三个目标冠词中的任意一个\s+:匹配冠词后面的一个或多个空格(确保移除冠词后不会留下多余空格)- 替换为空字符串,就完成了开头冠词的移除
运行结果
| title | title_cleaned |
|---|---|
| The Great Gatsby | Great Gatsby |
| a Tale of Two Cities | Tale of Two Cities |
| An apple a day | apple a day |
| 1984 | 1984 |
| the cat and the dog | cat and the dog |
可以看到,只有开头的冠词被移除,字符串中间的"a"和"the"完全不受影响,没有冠词的行也保持原样。
内容的提问来源于stack exchange,提问作者Elisa
相关产品推荐
相关产品推荐

