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

Pandas数据表剔除TG_plus列TG前缀的非循环实现方案咨询

Pandas非循环实现方案

我们可以用以下三种方案替代原生循环,性能和可读性都更好,按推荐优先级排序:

方案1:使用str.removeprefix(推荐,Pandas 1.4.0+支持)

这是专门用于移除前缀的方法,逻辑最直观,不会误删中间出现的相同内容:

# 移除TG列的CG前缀,strip用来去掉前缀后的多余空格
df["TG"] = df.apply(lambda row: row["TG"].removeprefix(row["CG"]).strip(), axis=1)
# 移除TG_plus列的TG前缀
df["TG_plus"] = df.apply(lambda row: row["TG_plus"].removeprefix(row["TG"]).strip(), axis=1)

方案2:字符串切片 + apply(兼容低版本Pandas)

和你原循环逻辑完全一致,用pandas的apply替代手动循环,写法更简洁:

df["TG"] = df.apply(lambda row: row["TG"][len(row["CG"]):].strip(), axis=1)
df["TG_plus"] = df.apply(lambda row: row["TG_plus"][len(row["TG"]):].strip(), axis=1)

方案3:纯向量化操作(性能最优,适合大数据量)

完全避免行遍历,性能比apply高10倍以上,适合10万行以上的大表:

# 处理TG列
cg_length = df["CG"].str.len()
df["TG"] = df["TG"].str.slice(cg_length).str.strip()

# 处理TG_plus列
tg_length = df["TG"].str.len()
df["TG_plus"] = df["TG_plus"].str.slice(tg_length).str.strip()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:09:00