I have Data Frame like below:
import pandas as pd
df = pd.DataFrame()
df["date"] = pd.date_range("2015", periods=5)
And list of holidays like: holidays = ["30.12.2014", "02.01.2015", "10.10.2015"]
And I would like to calculate for each date in df, number of days until next and since last holiday day from "holidays" list. So I need result like below (if of course I correctly calculate number of days, but somethng like below):
Use 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
for use and remove columns:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.