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

如何在Python的Pandas DataFrame中部分替换列中的字符串

问题:如何截取Pandas DataFrame中Comment列的指定部分?

原始DataFrame:

Name          Comment
1 Ama           Delay with coming home client to provide place he visited
2 Kofi          Enquiry on apples client to provide refund 
3 Kwame         Equiry on tables client advised with enquiry
4 Theo          Emotional challenge client to provide details
5 Isaiah        Eating on empty stomach client to confirm the issues

需要修改为:

Name          Comment
1 Ama           Delay with coming home
2 Kofi          Enquiry on apples 
3 Kwame         Enquiry on tables 
4 Theo          Emotional challenge 
5 Isaiah        Eating on empty stomach 

解决方案

可以通过以下几种简单方法实现:

方法1:字符串分割法

利用str.split()以固定分隔符" client "分割字符串,取分割后的第一部分:

import pandas as pd

# 构造原始数据
data = {
    "Name": ["Ama", "Kofi", "Kwame", "Theo", "Isaiah"],
    "Comment": [
        "Delay with coming home client to provide place he visited",
        "Enquiry on apples client to provide refund ",
        "Equiry on tables client advised with enquiry",
        "Emotional challenge client to provide details",
        "Eating on empty stomach client to confirm the issues"
    ]
}
df = pd.DataFrame(data, index=[1,2,3,4,5])

# 处理Comment列
df["Comment"] = df["Comment"].str.split(" client ").str[0]
print(df)

方法2:正则提取法

用str.extract()提取" client "之前的所有内容:

df["Comment"] = df["Comment"].str.extract(r"(.*?) client ", expand=False)

方法3:正则替换法

用str.replace()把" client "及后面的所有内容替换为空字符串:

df["Comment"] = df["Comment"].str.replace(r" client .*", "", regex=True)

内容的提问来源于stack exchange,提问作者alfred dowuona-owoo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 21:05:18