根据 Python Pandas 中数据框中的日期计算距下一个假期和自上次假期以来的天数?

Calculation of days until next and since last holiday based on date in Data Frame in Python Pandas?

我有如下数据框:

import pandas as pd
df = pd.DataFrame()
df["date"] = pd.date_range("2015", periods=5)

假期列表如下:holidays = ["30.12.2014", "02.01.2015", "10.10.2015"]

而且我想为 df 中的每个日期计算到下一个日期和从“假期”列表中的最后一个假期开始的天数。 所以我需要如下结果(如果我当然正确计算天数,但如下所示):

使用merge_asof here with default direction='backward' and direction='forward' for add column and then subtract with convert timedeltas to days by Series.dt.days and DataFrame.pop使用和删除列:

df = pd.DataFrame()
df["date"] = pd.date_range("2015", periods=5)

holidays = ["30.12.2014", "02.01.2015", "10.01.2015"]
holidays = pd.to_datetime(holidays, dayfirst=True)

df1 = pd.DataFrame({'date1':holidays})

df = pd.merge_asof(df, df1, left_on='date', right_on='date1', direction='forward')
df = pd.merge_asof(df, df1, left_on='date', right_on='date1')

df['until'] = df.pop('date1_x').sub(df['date']).dt.days
df['since'] = df['date'].sub(df.pop('date1_y')).dt.days
print (df)
        date  until  since
0 2015-01-01      1      2
1 2015-01-02      0      0
2 2015-01-03      7      1
3 2015-01-04      6      2
4 2015-01-05      5      3