You need to enable JavaScript to run this app. Python pandas DataFrame仅对符合条件的指定行执行自定义函数
优惠活动
大模型
产品
解决方案
定价
更多

Python pandas DataFrame仅对符合条件的指定行执行自定义函数

实现方案

核心逻辑是通过布尔掩码定位符合条件的行,仅对这部分行执行自定义函数,其余行保留原始值即可,修改后完整代码如下:

import pandas as pd

# 原有自定义函数保持不变
def parse_str_into_list(s):
    if str(s).startswith('[') and str(s).endswith(']'):
        return ' '.join(str(s).strip('[]').strip("'").split("', '"))
    return str(s)

def filter_restrict_words(row):
    targets = parse_str_into_list(row[0]).split(' ', -1)
    restricts = parse_str_into_list(row[1]).split(' ', -1)
    words_to_keep = []
    for word in targets:
        # 保留符合条件的词的逻辑
        if word not in words_to_keep:
            words_to_keep.append(word)
    return ' '.join(words_to_keep)

def uniqueList(row):
    words = row.split(" ")
    unique = words[0]
    for w in words:
        if w.lower() not in unique.lower():
            unique = unique + " " + w
    return unique

# --------------------------新增条件筛选逻辑--------------------------
# 1. 生成布尔掩码:仅选中column1取值为指定字符串的行
mask = df['column1'] == 'this is a sentence'

col_target = 'column3'
col_restrict = 'column2'

# 2. 初始化输出列为原始column3值(不符合条件的行直接保留该值)
df['output_required'] = df['column3'].astype(str)
# 仅对符合条件的行执行拼接逻辑,匹配示例的输出规则
df.loc[mask, 'Title'] = df.loc[mask, [col_target, col_restrict]].apply(lambda x: filter_restrict_words(x), axis=1)
df.loc[mask, 'output_required'] = df.loc[mask, 'Title'].map(str) + ' ' + df.loc[mask, col_restrict].map(str)

# 3. 仅对符合条件的行执行去重逻辑,其余行保留Correction_Value原始值
# 注意:若Correction_Value列尚未初始化,先按业务规则完成初始化再执行本行
df.loc[mask, "Correction_Value"] = df.loc[mask, "Correction_Value"].apply(uniqueList)
修改说明
  • 新增的mask变量只会命中需要处理的行,所有函数计算仅作用于这部分数据
  • 不符合条件的行不会进入处理逻辑,完全保留原始取值,和你给出的示例效果完全匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 07:54:05