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

如何从层级结构的Pandas DataFrame生成指定格式的布尔表达式

需求:基于层级结构的Pandas DataFrame生成嵌套布尔表达式

给定的层级结构DataFrame:

import pandas as pd

df = pd.DataFrame(
    {
        "id": [1, 2, 3, 4, 5, 6, 7, 8],
        "parent_id": [0, 0, 1, 1, 2, 2, 4, 4],
        "value": ["a>2", "b<4", "d>5", "e<3", "h>1", "i>10", "f>3", "g>2"],
    }
)

(注:原代码中value列表元素需为字符串形式,否则会触发语法错误,此处补充引号修正)

需要生成的布尔表达式字符串:

"or(and (a > 2, 
     or(d > 5, 
        and (e<3,
             or (f > 3, 
                 g > 2)
            )  
       )
    ),

    and(b < 4,
        or(h > 1,
           i > 10)
       )
  )"

规则说明:

  • 所有子节点需作为OR函数的参数
  • 父节点与其子节点需作为AND函数的参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 13:47:03