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

修改Pandas apply行处理函数实现Account Codes自定义匹配规则

Pandas Account Codes匹配规则修改方案

逐行判断时单个值不需要用isin()方法,直接用Python原生的in运算符判断是否在列表内即可,以下是修改后的代码:

def compute_match_codes(row):
    codes = ['D1','D2','D4','D3']
    # 先判断是否满足特殊匹配规则条件
    special_cond = (row['Cur'] == 'USD' 
                    and row['branch'] == 31 
                    and row['Account_Codes'] in ['D12', 'D55'])
    if special_cond:
        if row['Account_Codes_v2'] in codes:
            return 'MatchOnCodes'
    # 特殊规则不满足时走原有匹配逻辑
    if row['Account_Codes'] == row['Account_Codes_v2']:
        return 'MatchOnCodes'
    else:
        return 'MismatchOnCodes'

原有concat写法可以简化,直接给新列赋值即可,不需要额外拼接操作:

df['match_result'] = df.apply(compute_match_codes, axis=1)

结果验证

执行后输出的match_result列完全符合预期:

  • 第0行:MatchOnCodes(符合特殊规则,Account_Codes_v2=D3在codes列表内)
  • 第1行:MatchOnCodes
  • 第2行:MatchOnCodes
  • 第3行:MismatchOnCodes(branch=6不满足特殊规则,且两个codes值不等)
  • 第4行:MatchOnCodes
  • 第5行:MatchOnCodes(符合特殊规则,Account_Codes_v2=D2在codes列表内)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 10:06:04