Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

python - Counting the business days between two series

Is there a better way than bdate_range() to measure business days between two columns of dates via pandas?

df = pd.DataFrame({ 'A' : ['1/1/2013', '2/2/2013', '3/3/2013'],
 'B': ['1/12/2013', '4/4/2013', '3/3/2013']})
print df
df['A'] = pd.to_datetime(df['A'])
df['B'] = pd.to_datetime(df['B'])
f = lambda x: len(pd.bdate_range(x['A'], x['B']))
df['DIFF'] = df.apply(f, axis=1)
print df

With output of:

          A          B
0  1/1/2013  1/12/2013
1  2/2/2013   4/4/2013
2  3/3/2013   3/3/2013
                    A                   B  DIFF
0 2013-01-01 00:00:00 2013-01-12 00:00:00     9
1 2013-02-02 00:00:00 2013-04-04 00:00:00    44
2 2013-03-03 00:00:00 2013-03-03 00:00:00     0

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

brian_the_bungler was onto the most efficient way of doing this using numpy's busday_count:

import numpy as np
A = [d.date() for d in df['A']]
B = [d.date() for d in df['B']]
df['DIFF'] = np.busday_count(A, B)
print df

On my machine this is 300x faster on your test case, and 1000s of times faster on much larger arrays of dates


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...