You need to enable JavaScript to run this app. pandas如何基于动态多条件与运算生成新决策列
优惠活动
大模型
产品
解决方案
定价
更多

pandas如何基于动态多条件与运算生成新决策列

实现代码

你可以通过如下可直接运行的函数完成需求,支持动态长度的条件配置,也兼容==/!=/>/</>=/<=/in/not in等常用判断逻辑:

import pandas as pd
from functools import reduce
import operator

def add_decision_column(df, assign_header, conditions):
    # 运算符映射:把配置里的条件字符串对应到实际判断逻辑
    op_map = {
        '==': operator.eq,
        '!=': operator.ne,
        '>': operator.gt,
        '<': operator.lt,
        '>=': operator.ge,
        '<=': operator.le,
        'in': lambda s, v: s.isin(v),
        'not in': lambda s, v: ~s.isin(v)
    }
    # 生成所有布尔条件列表
    condition_list = []
    for cond in conditions:
        header = cond['header']
        op = cond['condition']
        values = cond['values']
        condition_list.append(op_map[op](df[header], values))
    # 对所有条件做批量逻辑与运算
    final_mask = reduce(operator.and_, condition_list)
    # 赋值新列
    df[assign_header] = final_mask
    return df

测试效果

# 示例数据初始化
x = [[1,2,3,4,5],[1,2,4,4,3],[2,4,5,6,7]]
columns = ['a','b','c','d','e']
df = pd.DataFrame(data = x, columns = columns)

# 示例条件配置
conditions = [
    {
        'header' : 'a',
        'condition' : '==',
        'values' : [1]
    },
    {
        'header' : 'b',
        'condition' : '==',
        'values' : [2]
    }
]
assignHeader = 'decision'

# 调用函数
df = add_decision_column(df, assignHeader, conditions)
print(df)

输出结果和预期完全一致:

a  b  c  d  e  decision
0  1  2  3  4  5      True
1  1  2  4  4  3      True
2  2  4  5  6  7     False

后续需要新增判断规则时,直接往conditions数组里加对应配置即可,不需要修改函数逻辑,支持任意长度的条件组合。如果需要处理无配置条件的场景,可以在reduce执行前增加判断,无条件时默认返回全True或者全False的布尔序列即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 03:15:01