熊猫-如何根据自定义日历计算两个日期的黑白天数

我的问题很简单,所以我希望有一个简单的解决方案。我想计算两个日期之间的天数,而不是使用完整的日历日或工作日或带假日日历的工作日,我想以日期列表的形式提供我自己的“日历”。


假设我的日期是 ['2019-01-01', '2010-01-03', '2019-01-04', '2019-01-10']。我希望“2019-01-01”和“2019-01-03”之间的日期返回 1。“2019-01-03”和“2019-01-10”之间的日期应返回 2。


谢谢!


# This produces standard calendar days between-

dates_list = df.index

x = dates_list[1] - dates_list[0]


# This produces days according to numpy businessdaycal:

cal = np.busdaycalendar()

x = np.busday_count('2019-01-01', '2019-01-03', busdaycal=cal)


# This works, but requires multiple steps so prob inefficient:

dates_list = df.index

all_dates = pd.date_range(dates_list[0], dates_list[1])

holidays = [d.date() for d in all_dates if d not in dates_list]

cal = np.busdaycalendar(holidays=holidays)

x = np.busday_count('2019-01-01', '2019-01-03', busdaycal=cal)


凤凰求蛊
浏览 82回答 2
2回答

月关宝盒

这是我所拥有的最好的。我尝试了@RichieV 的 pd.Series.between() 和以下方法,速度更快:dates_list = df.indexall_dates = pd.date_range(dates_list[0], dates_list[1])holidays = [d.date() for d in all_dates if d not in dates_list]cal = np.busdaycalendar(holidays=holidays)x = np.busday_count('2019-01-01', '2019-01-03', busdaycal=cal)

人到中年有点甜

这是一种方法:import pandas as pdmy_cal = pd.Series(    data=1,     index=pd.date_range(start='2020-01-01', periods=100, freq='D'))# set your own 'holidays' to zero here# cumulative sum won't count your custom 'holidays'my_cal = my_cal.cumsum()# use like this (this could be wrapped in a function)days_between = my_cal['2020-01-03'] - my_cal['2020-01-01']print(days_between)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python