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

pandas.apply调用businessDuration报错,求技术解决方案

解决business_duration结合pandas.apply计算工作日时长的参数传递错误

问题场景

读取数据库工单数据后,希望通过business_duration库计算每条工单Open_Date与Close_Date之间的工作日时长,使用pandas.apply创建新列时触发错误:

the truth value of a series is ambiguous

出错代码片段:

df['x'] = df.apply(lambda x: businessDuration(startdate=df['Open_Date'], enddate=df['Close_Date'], starttime=biz_open_time, endtime=biz_close_time, holidaylist=US_holiday_list,unit=unit_hour), axis=1)

错误原因

在lambda函数中,错误地传递了整个DataFrame的Open_Date和Close_Date列(Series对象)给businessDuration,而该函数需要单个datetime类型的日期值作为入参。当函数内部对Series进行布尔判断时,就会触发"truth value of a series is ambiguous"的歧义错误。

修正方案

  1. 确保日期列格式正确:从数据库读取的日期可能是字符串类型,需转换为datetime格式,避免类型不兼容问题。
  2. 正确传递行级参数:在apply的lambda函数中,使用当前行的参数(而非整个列)来获取单个日期值,即通过row['Open_Date']和row['Close_Date']传递。
  3. 清理冗余代码:移除重复的pandas导入语句,删除未定义的df_incident删除操作。

完整修正代码

import pandas as pd
import sqlite3
from business_duration import businessDuration
import holidays as pyholidays
from datetime import time

def main():
    print("Connecting to databases...")
    cn_sndb = sqlite3.connect(r"E:\Database\sndb.sqlite")
    
    print("Importing Data...")
    q1 = """
        select RITM, Cat_Item, Request_Type, RITM_Stage, RITM_State, Open_Date, Close_Date
        from NewComputer
        where ritm_stage not like '%cancel%'
    """
    df = pd.read_sql(q1, cn_sndb)
    
    # 转换日期列为datetime格式
    df['Open_Date'] = pd.to_datetime(df['Open_Date'])
    df['Close_Date'] = pd.to_datetime(df['Close_Date'])
    
    # 配置业务时间与假期
    biz_open_time = time(7, 0, 0)
    biz_close_time = time(17, 0, 0)
    US_holiday_list = pyholidays.US(state='VA')
    unit_hour = 'day'
    
    # 正确使用apply传递行级参数
    df['x'] = df.apply(
        lambda row: businessDuration(
            startdate=row['Open_Date'],
            enddate=row['Close_Date'],
            starttime=biz_open_time,
            endtime=biz_close_time,
            holidaylist=US_holiday_list,
            unit=unit_hour
        ),
        axis=1
    )
    
    # 可根据需求添加数据保存或输出逻辑
    # print(df.head())

if __name__ == "__main__":
    main()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 17:36:16