user9517026
user9517026

Reputation: 123

Pandas, is a date holiday?

I have the following pandas dataframe. The dates are with time:

from pandas.tseries.holiday import USFederalHolidayCalendar
import pandas as pd<BR>
df = pd.DataFrame([[6,0,"2016-01-02 01:00:00",0.0],
                   [7,0,"2016-07-04 02:00:00",0.0]])

cal = USFederalHolidayCalendar()
holidays = cal.holidays(start='2014-01-01', end='2018-12-31')

I want to add a new boolean column with True/False if the date is holiday or not. Tried df["hd"] = df[2].isin(holidays), but it doesn't work because of time digits.

Upvotes: 0

Views: 964

Answers (1)

jezrael
jezrael

Reputation: 863611

Use Series.dt.floor or Series.dt.normalize for remove times:

df[2] = pd.to_datetime(df[2])

df["hd"] = df[2].dt.floor('d').isin(holidays)
#alternative
df["hd"] = df[2].dt.normalize().isin(holidays)

print (df)
   0  1                   2    3     hd
0  6  0 2016-01-02 01:00:00  0.0  False
1  7  0 2016-07-04 02:00:00  0.0   True

Upvotes: 2

Related Questions