Python3 Pandas计算有效工作时长:businessDuration批量调用失败求助
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
businessDurationwithnumpy.vectorize(this is still a loop under the hood, but optimized for speed) - Alternative libraries like
pandas-businesswhich offer better vectorized support for working hours calculations
内容的提问来源于stack exchange,提问作者horton

