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

在Pandas DataFrame每行中查找并移除分隔后的最长子串

移除Pandas列中|分隔的最长子串(保留短标签)

问题场景

将CSV导入Pandas DataFrame后,目标列内容原本以转义逗号分隔,其中包含1个长串产品描述和若干短标签。已通过代码将转义逗号替换为|,现在需要移除这个最长的子串,只保留短标签并以|连接。

数据示例

  • 替换转义逗号后的中间数据:
Anthropologie Dolan Women's S Green Long Sleeves Tie Front Dress|Girl| Woman| USA| American| Chic
Button|Logo|Blue Skinny Crop Denim Raw Hem Ankle Denim Jeans
  • 期望最终输出:
Girl | Woman | USA | American | Chic
Button | Logo

之前的错误尝试

最初假设长串始终在开头,使用以下代码:

woo_product_list[col].mask(woo_product_list[col].str.len() > 40, woo_product_list[col].str.split('|', n=1).str.get(-1), inplace=True)

但该方案无法处理长串在末尾的情况(如第二行数据),得到错误结果:

Girl| Woman| USA| American| Chic
Logo|Blue Skinny Crop Denim Raw Hem Ankle Denim Jeans

解决方案

通过拆分字符串为列表,找到并移除其中长度最大的子串,再将剩余短标签重新连接:

for col in config["wooAttributeReplace"]:
    # 替换转义逗号为|分隔符
    woo_product_list[col] = woo_product_list[col].replace(r'\\,', '|', regex=True)
    
    # 处理每个单元格:拆分→移除最长子串→重新连接
    woo_product_list[col] = woo_product_list[col].str.split('|').apply(
        lambda x: ' | '.join(
            [s.strip() for s in x if len(s.strip()) != max(len(s.strip()) for s in x)]
        )
    )

代码说明

  1. 拆分字符串:用str.split('|')将每个单元格的内容拆分为子串列表;
  2. 识别最长子串:计算所有子串(去除首尾空格后)的最大长度;
  3. 筛选并连接:过滤掉长度等于最大长度的子串,将剩余子串去除首尾空格后用|连接。

该方案不受长串位置影响,无论长串在开头、中间还是末尾,都能准确移除,得到符合需求的短标签结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 20:56:28