Higashi Yutaka
Higashi Yutaka

Reputation: 181

Flag holidays in DataFrame on python3

I have a pandas DataFrame that have timestamp and have a set of datetimes of holidays

{datetime.date(2016, 1, 1), datetime.date(2016, 3, 25), datetime.date(2016, 3, 27), datetime.date(2016, 3, 28), datetime.date(2016, 5, 2), datetime.date(2016, 5, 30), datetime.date(2016, 8, 29), datetime.date(2016, 12, 25), datetime.date(2016, 12, 26), datetime.date(2016, 12, 27)}

I want to flag if it's a holiday or not. It would be great if you could teach me how to do that. Thank you!

    timestamp
0   2016-01-01 00:00:00
1   2016-01-01 00:00:00
2   2016-01-01 00:00:00
3   2016-01-01 00:00:00
4   2016-01-01 00:00:00
... ...
20216095    2016-12-31 23:00:00
20216096    2016-12-31 23:00:00
20216097    2016-12-31 23:00:00
20216098    2016-12-31 23:00:00
20216099    2016-12-31 23:00:00

Upvotes: 3

Views: 558

Answers (1)

Vishnudev Krishnadas
Vishnudev Krishnadas

Reputation: 10960

Ensure timestamp column is of type datetime and then use date to compare with the holidays set.

df['timestamp'] = pd.to_datetime(df['timestamp'])
df['holidays'] = pd.np.where(df['timestamp'].dt.date.isin(holidays), 1, 0)

Upvotes: 1

Related Questions