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

Python3 Pandas计算有效工作时长:businessDuration批量调用失败求助

Calculating Effective Working Duration in Pandas with business-duration: Fixing Batch Processing Issues

Hey there! Let's break down why passing entire Pandas columns to businessDuration isn't working, and how to get your Column C up and running smoothly.

Why Batch Column Input Fails

The businessDuration function from the business-duration package is designed to handle single datetime values for its startdate and enddate parameters—not entire Pandas Series (your Column A and Column B). When you pass a whole column, the function can't automatically iterate over each row's start/end time pair; it expects individual datetime objects, not a collection of them. That’s exactly why your single-row test works perfectly, but the batch call throws an error.

How to Fix It: Process Rows One by One

The most straightforward solution is to use Pandas' apply method to run businessDuration on each row individually. Here's a step-by-step implementation:

First, ensure your date columns are properly converted to datetime type (skip this if you’ve already done it):

import pandas as pd
from business_duration import businessDuration

# Convert columns to datetime format
data['A'] = pd.to_datetime(data['A'])
data['B'] = pd.to_datetime(data['B'])

Then, use apply to calculate the working duration for each row and populate Column C:

# Calculate working duration row-by-row
data['C'] = data.apply(
    lambda row: businessDuration(startdate=row['A'], enddate=row['B'], unit='hour'),
    axis=1  # This tells apply to operate on rows instead of columns
)

Notes for Larger Datasets

If you’re working with a very large dataset, apply can be a bit slow since it’s essentially looping through rows. Unfortunately, the business-duration package doesn’t support vectorized operations (processing entire columns at once) out of the box. If speed becomes an issue, you could explore:

  • Wrapping businessDuration with numpy.vectorize (this is still a loop under the hood, but optimized for speed)
  • Alternative libraries like pandas-business which offer better vectorized support for working hours calculations

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:18:04