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

如何通过for循环创建字符串搜索标记列并合并为统一汇总列

实现代码

你可以直接用下面的代码完成需求:

import pandas as pd

# 示例数据,可替换为你自己的df1x
data = {"Text Column": [
    "the cat and dog ate the hamster",
    "the cat ate the hamster",
    "the dog ate the hamster",
    "the hamster ate his dinner"
]}
df1x = pd.DataFrame(data)

# 定义待搜索的字符串列表
strings = ['Cat','Dog','Hamster']

# 1. 生成每个字符串对应的布尔标记列
for s in strings:
    df1x[s] = df1x["Text Column"].str.contains(s, case=False, regex=True)

# 2. 生成合并列,拼接所有命中的字符串
df1x['Combined'] = df1x.apply(
    lambda row: ', '.join([s for s in strings if row[s]]),
    axis=1
)

# 输出查看结果
print(df1x)

补充说明

  • 标记列默认是布尔类型True/False,如果需要转换为T/F的字符串格式,可以将生成标记列的代码替换为:
    df1x[s] = df1x["Text Column"].str.contains(s, case=False, regex=True).map({True: 'T', False: 'F'})
    
  • 如果待搜索的字符串包含.、*、?等正则特殊字符,且不需要正则匹配规则,建议将str.contains的参数regex=True改为regex=False,避免匹配异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 00:39:01