1 回答
TA贡献1801条经验 获得超16个赞
您可以使用 numpy datetime 函数和一些包装:
import numpy as np
def countWeekDays(fromDate='2020-03-03', toDate='2020-06-03'):
d = np.arange(fromDate, toDate, dtype=np.datetime64)
weekdays = d[np.is_busday(d, busdaycal=calendar())]
workDays = [(m, np.array([i for i in weekdays if i.item().month==m]).size) for m in range(1,13)]
return workDays
def calendar():
#set work week mask and optional holidays array
return np.busdaycalendar(weekmask='1111100', holidays=['2020-01-01','2020-01-20','2020-02-17','2020-05-25','2020-07-03','2020-09-07','2020-10-12','2020-11-11','2020-11-26','2020-12-25'])
结果:
>>> countWeekDays()
[(1, 0), (2, 0), (3, 21), (4, 22), (5, 20), (6, 2), (7, 0), (8, 0), (9, 0), (10, 0), (11, 0), (12, 0)]
这是对您的代码的修改,以构建与我的函数一起使用以获取工作日的数据框。我认为您遇到的错误是由于构建和修改 Dataframe 的方式造成的。我的经验是数据框很难修改,最好将数据放在一起,然后从完整的数据集中创建数据框:
def applyDays():
data = [{'start_date': '2020-03-03', 'end_date' : '2020-06-18'},
{'start_date': '2020-06-03', 'end_date' : '2020-09-18'}]
return countWeekDays(data)
def countWeekDays(lst): #, result_type):
months = ['start_date','end_date', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
data = []
for row in lst:
fromDate = row['start_date'] # df['PO Creation Date']
toDate = row['end_date'] #df['PO Expected Delivery Date']
d = np.arange(fromDate, toDate, dtype=np.datetime64)
weekdays = d[np.is_busday(d, busdaycal=calendar())]
data.append([fromDate, toDate] + [np.array([i for i in weekdays if i.item().month==m]).size for m in range(1,13)])
return pd.DataFrame(data, columns=months)
数据框结果:
applyDays()
Out[6]:
start_date end_date Jan Feb Mar Apr May Jun Jul Aug Sep Oct \
0 2020-03-03 2020-06-18 0 0 21 22 20 13 0 0 0 0
1 2020-06-03 2020-09-18 0 0 0 0 0 20 22 21 12 0
Nov Dec
0 0 0
1 0 0
添加回答
举报