You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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+:匹配冠词后面的一个或多个空格(确保移除冠词后不会留下多余空格)
  • 替换为空字符串,就完成了开头冠词的移除

运行结果

titletitle_cleaned
The Great GatsbyGreat Gatsby
a Tale of Two CitiesTale of Two Cities
An apple a dayapple a day
19841984
the cat and the dogcat and the dog

可以看到,只有开头的冠词被移除,字符串中间的"a"和"the"完全不受影响,没有冠词的行也保持原样。

内容的提问来源于stack exchange,提问作者Elisa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 00:50:31