计算两个日期之间的周末(星期六和星期日)的数量

时间:2019-05-04 16:07:46

标签: pandas python-datetime

我有一个带有两个日期列的数据框,一个开始日期和一个结束日期。如何使用pandas或python date-times查找开始日期和结束日期之间的周末数量

我知道熊猫有DatetimeIndex,从星期一开始,它在一周的每一天都返回0到6的值。

# create a data-frame
import pandas as pd
df = pd.DataFrame({'start_date':['4/5/19','4/5/19','1/5/19','28/4/19'],
                   'end_date': ['4/5/19','5/5/19','4/5/19','5/5/19']})

# convert objects to datetime format
df['start_date'] = pd.to_datetime(df['start_date'], dayfirst=True)
df['end_date'] = pd.to_datetime(df['end_date'], dayfirst=True)

# Trying to get the date index between dates as a prelim step but fails
pd.DatetimeIndex(df['end_date'] - df['start_date']).weekday

我希望结果是这样的:(weekend_count包括开始和结束日期)

start_date  end_date    weekend_count
4/5/2019    4/5/2019    1
4/5/2019    5/5/2019    2
1/5/2019    4/5/2019    1
28/4/2019   5/5/2019    3

2 个答案:

答案 0 :(得分:2)

IIUC

df['New']=[pd.date_range(x,y).weekday.isin([5,6]).sum() for x , y in zip(df.start_date,df.end_date)]
df
  start_date   end_date  New
0 2019-05-04 2019-05-04    1
1 2019-05-04 2019-05-05    2
2 2019-05-01 2019-05-04    1
3 2019-04-28 2019-05-05    3

答案 1 :(得分:1)

尝试:

df['weekend_count']=((df.end_date-df.start_date).dt.days+1)-np.busday_count(
                     df.start_date.dt.date,df.end_date.dt.date)
print(df)

  start_date   end_date  weekend_count
0 2019-05-04 2019-05-04              1
1 2019-05-04 2019-05-05              2
2 2019-05-01 2019-05-04              1
3 2019-04-28 2019-05-05              3