Python Forum
Checking if date is holiday in a datetimeindex
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Checking if date is holiday in a datetimeindex
#1
Hello Everybody!!

I have one column in a dataframe that has a set of dates as pandas.series, like these examples:

1458641 2016-04-22 06:57:41
1458642 2016-01-05 15:56:26
....

And im trying to set if the date is an american holiday, so i tried this:

...

from pandas.tseries.holiday import USFederalHolidayCalendar
cal = USFederalHolidayCalendar()
holidays = pd.to_datetime(cal.holidays(start='2016-01-01', end='2016-06-30'))
completo['IsHoliday'] = pd.to_datetime(completo['pickup_datetime']).dt.date in holidays
print(completo[completo['IsHoliday']==True])
...


But all dates were set as FALSE, even with date '2016-01-01' in the both dataframe column and datettimeindex.

Can Anybody help me!?

Thx,
Reply
#2
I am not familiar with pandas (pandas is cool), but if you're iterating over the input line by line, you can parse it. I do it with the python stdlib:

import datetime
from io import StringIO


text = """0 2016-01-01 0000000
1458641 2016-04-22 06:57:41
1458642 2016-01-05 15:56:26"""

like_file = StringIO(text)
# acts as a file, supports also iteration which gives you line by line in a loop

# using your holidays object
for line in like_file:
    _, date, time = line.split()
    date = datetime.datetime.strptime(date, '%Y-%M-%d').date() # this converts the str to a date object
    if date in holidays:
    # here is the magic, the in operator works also with pandas data frames
    # this should also work with a field a column from a pandas data frame
        print(line)
You just need a method to convert your input data to a pandas data frame and do the right job to parse the columns for each row.
For pandas there are many helper functions to make it easier as my example with datetime.
I guess pandas do also have a filter function for this task, that you don't need to iterate like me over the data set by yourself.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  replace nan values by mean group by date.year, date.month wissam1974 5 8,332 Feb-19-2020, 06:25 PM
Last Post: AnkitGupta
  Finding date count from a list of date range in pandas trillerducas72 0 2,720 May-24-2018, 02:30 AM
Last Post: trillerducas72

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020