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

Pandas基于indicator_df计算input_df公式生成output_df实现问题

需求说明

我们有两个数据框:

  • input_df:存储每个患者对应的KPI计算公式
  • indicator_df:存储每个患者的各指标取值,其中1代表真,0代表假

需要按照以下规则计算得到最终的output_df:

  1. 公式中的+代表或运算,运算规则:1+1=1、1+0=1、0+0=0
  2. 公式中的*代表与运算,运算规则:1*1=1、1*0=0、0*0=0
  3. 如果公式为空/NaN,或者公式中引用的指标不在indicator_df列中,对应取值为0

原始数据定义代码
import pandas as pd

input_df = pd.DataFrame({'PatientID': [1,2,3,4,5], 'KPI_Key1': ['(C602+C603)','(C605+C606)','75','(32*(C603+234))','L239'] , 'KPI_Key2' : ['C601','C602','L239+C602','75',''] , 'KPI_Key3' : ['','','','','C601']})
indicator_df = pd.DataFrame({'PatientID': [1,2,3,4,5,6,7,8],'99' : ['1','0','1','0','1','0','1','0'],'75' : ['0','0','1','0','0','1','1','0'],'C604' : ['1','0','1','0','1','0','1','0'],'C602' : ['0','0','1','0','1','0','1','0'],'C601' : ['1','0','0','0','1','0','1','0'],'C603' : ['0','0','1','1','1','0','1','0'],'C605' : ['0','1','1','0','0','0','1','0'],'C606' : ['0','1','1','1','1','0','1','0'],'44' : ['1','0','1','0','1','0','1','0'],'L239' : ['0','0','1','1','1','0','1','0'], '32' : ['1','0','1','0','1','0','1','0'],}).set_index('PatientID')

完整实现代码
import re

# 1. 将indicator_df的值转换为整数类型
indicator_df = indicator_df.astype(int)
valid_indicators = set(indicator_df.columns)

# 2. 定义KPI公式计算函数
def calc_kpi(patient_id, formula):
    # 处理空值、空字符串
    if pd.isna(formula) or str(formula).strip() == '':
        return 0
    formula = str(formula).strip()
    # 替换运算符为Python对应位运算符
    formula = formula.replace('+', '|').replace('*', '&')
    # 提取公式中所有指标标识符
    indicators = re.findall(r'[A-Z0-9]+', formula)
    # 替换指标为对应取值
    for ind in indicators:
        val = indicator_df.loc[patient_id, ind] if ind in valid_indicators else 0
        formula = re.sub(r'\b' + re.escape(ind) + r'\b', str(val), formula)
    # 执行计算返回结果
    try:
        return int(eval(formula))
    except:
        return 0

# 3. 生成输出结果
output_df = input_df.copy()
kpi_cols = ['KPI_Key1', 'KPI_Key2', 'KPI_Key3']
for col in kpi_cols:
    output_df[col] = output_df.apply(lambda row: calc_kpi(row['PatientID'], row[col]), axis=1)

print(output_df)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:57:01