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

如何移除DataFrame字符串中从mode开始的后续内容?

移除DataFrame字符串中从“mode”开始到末尾的内容

问题场景

现有包含如下数据的DataFrame:

import pandas as pd
df = pd.DataFrame({
    'data': [
        "First: This is the sentence good mode:one line",
        "Second: This sentence is also good mode:one line",
        "Third: this sentence is too long mode:two lines"
    ]
})

需要将每个字符串中从“mode”(含)开始到末尾的所有内容移除,最终结果如下:

df['data'] = [
    "First: This is the sentence good",
    "Second: This sentence is also good",
    "Third: this sentence is too long"
]

错误原因分析

你之前的代码仅针对特定字符串"mode: one line"做替换,但实际数据中mode后的内容并不统一(比如存在mode:one line和mode:two lines两种格式),且正则匹配逻辑未覆盖完整的目标内容,导致仅移除了部分字符。

正确解决方案

使用正则表达式匹配从mode开始到字符串结尾的所有内容,一次性完成统一替换:

df['data'] = df['data'].str.replace(r'\s*mode.*', '', regex=True)
  • \s*:匹配mode前可能存在的空格,避免处理后字符串末尾残留多余空格
  • mode.*:匹配mode本身以及后面的所有字符(.*表示任意字符任意次数)
  • regex=True:启用正则匹配模式,确保表达式生效

执行上述代码后即可得到期望的处理结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:36:29