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

Pandas中排除限制列表字符串的两列拼接问题

问题解决:新增限制条件避免特定words值的拼接操作

原代码实现了在type为Is there a match with the Words?的行中,提取sentence中不在words里的内容,再和words拼接。现在需要新增规则:当words列的值属于restricted = ['not present', 'for sale', 'unknown']时,不执行拼接,直接保留sentence中未匹配的内容。

修改后的完整代码

import string
import numpy as np
import pandas as pd

def check(row):
    # 仅转换当前行的字段类型,避免全局修改引发的重复转换问题
    sentence = str(row['sentence'])
    words = str(row['words'])
    left = sentence.split()
    right = words.split()
    unmatched = []
    for y in left:
        word = "".join([x for x in y.lower() if x not in string.punctuation])
        if word not in [v.lower() for v in right]:
            unmatched.append(y)
    return " ".join(unmatched)

restricted = ['not present', 'for sale', 'unknown']
mask = df['type'] == 'Is there a match with the Words?'
df.loc[mask, 'new'] = df.loc[mask, :].apply(check, axis=1)

# 新增限制条件:仅当words不在限制列表且满足原mask条件时,才执行拼接
df['new'] = np.where(
    (~df['words'].isin(restricted)) & mask,
    df['new'] + ' ' + df['words'], 
    df['new']
)

df['new'] = df['new'].str.replace('nan', '')
df['new'] = df['new'].fillna("")

关键修改说明

  • 优化check函数:原函数直接修改整个DataFrame的列类型,会导致apply重复执行时多次转换,改为仅处理当前行的字段值,消除全局副作用。
  • 新增限制判断:在np.where中加入~df['words'].isin(restricted)条件,只有同时满足type匹配、words不在限制列表两个条件时,才执行拼接操作;否则直接保留check函数返回的未匹配内容。
  • 保留原空值处理逻辑,确保输出格式统一。

效果验证

针对示例输入:

wordssentenceoutput
unknownThis is a new paintThis is a new paint
brownThis is a new itemThis is a new item brown
for saleThe product is newThe product is new

修改后的代码会输出符合预期的结果,限制列表中的值不会被拼接到最终结果里。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 23:15:33