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函数返回的未匹配内容。 - 保留原空值处理逻辑,确保输出格式统一。
效果验证
针对示例输入:
| words | sentence | output |
|---|---|---|
| unknown | This is a new paint | This is a new paint |
| brown | This is a new item | This is a new item brown |
| for sale | The product is new | The product is new |
修改后的代码会输出符合预期的结果,限制列表中的值不会被拼接到最终结果里。
内容的提问来源于stack exchange,提问作者Isa
相关产品推荐
相关产品推荐

