【问题标题】:Applying Nested If condition to dataframe -Python将嵌套 If 条件应用于数据框 -Python
【发布时间】:2020-02-23 08:34:56
【问题描述】:

我正在连接到 SQL 数据库并在凌晨 4 点到 6 点之间生成 2 小时睡眠时间为 5 分钟的数据帧,并尝试检查作业状态,以下是我正在尝试实施的条件。

遍历所有工作,我想做的是:

如果有任何作业正在运行,并检查它是否在估计的时间内完成。

  • 如果是,则打印(“在预计时间内运行良好”) else print("已超出预计时间")。
  • 否则检查最后一个作业是否已完成,然后打印(“所有作业已完成”)。

以下是数据:

我的代码:

i=0
while i <12:
    
    todays_run="select * from table where getdate()=startdate"  /*Checking for rundate as todays date*/
    result=pd.read_sql(todays_run,sql_conn)
    if result.empty:
        print(' No jobs are running  :')
    elif result[result.status=='RUNNING' and result.start_date <result.estimated_end]:
        print("Below  jobs are currently running with estimated time \n\n ",result)
    else print("Jobs taking long time",<job_name>)
    elsif result[result.status=='COMPLETED' and result.jobname='A']
        print("all jobs are completed \n \n ")
    time.sleep(60)
exit(1)

我收到一个错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

这可以用python实现吗?

【问题讨论】:

    标签: python sql-server dataframe if-statement


    【解决方案1】:

    系列面具可以在这种情况下提供帮助。应用于 DataFrame 的每一行的每个逻辑条件都会生成一个 True/False 值的列表/系列。

    然后您可以使用df.loc[mask] 访问行,并将逻辑“and”转换为按位掩码“&”以将掩码组合在一起。我也喜欢根据逻辑测试说mask.any()mask.all()。这些技巧可以帮助我完成您想要实现的步骤。

    这是您尝试实现的一些想法,已转换为系列掩码。

    for i in range(12):
        # Checking for rundate as todays date
        todays_run="select * from table where getdate()=startdate"
        result=pd.read_sql(todays_run,sql_conn)
        running_mask = result["status"] == 'RUNNING'
        completed_mask = result["status"] == 'COMPLETED'
        jobname_a_mask = result["jobname"] == 'A'
        estimated_mask = result["start_date"] < result["estimated_end"]
        if result.empty:
            print(' No jobs are running  :')
        elif (running_mask & estimated_mask).any():
            print("Below  jobs are currently running with estimated time \n\n ",
                result.loc[running_mask & estimated_mask])
        else (jobname_a_mask & completed_mask).all():
            print("all jobs are completed \n \n ")
        time.sleep(60)
    exit(1)
    

    【讨论】:

      【解决方案2】:

      在您的elif 条件中,您可能同时评估多行。这就是您收到该错误的原因。 如果您不在乎有多少行符合您的条件,您可以尝试:

      elif (result[result.status=='RUNNING' and result.start_date <result.estimated_end]).any()
      

      或者,如果您需要所有行都符合您的条件,请将 .any() 替换为 .all()

      【讨论】:

        猜你喜欢
        • 2019-10-15
        • 2017-03-02
        • 1970-01-01
        • 2021-07-15
        • 2013-03-29
        • 1970-01-01
        • 1970-01-01
        • 2021-08-12
        • 1970-01-01
        相关资源
        最近更新 更多