Pandas Determine if Date Is In List of Dates

So I have a column with a list of dates in it. I have a list/array with a set of specific dates in it. I want to assign a new column in my dataframe with true/false as to whether or not the specific date was in the list. I have the following, but it doesn't work and I'm not sure why.

__DATELIST = [date(2017, 7, 4), date(2016, 7, 4), ...]

def isholiday(x):
   return x in __DATELIST

df['isholiday'] = df['date'].apply(isholiday)

Any thoughts? The above is always false.

2 answers

  • answered 2018-03-20 23:46 Battery_Al

    You should try using datetime.datetime objects instead of objects to construct your list of dates. Your data types need to be equivalent.

  • answered 2018-03-20 23:46 cᴏʟᴅsᴘᴇᴇᴅ

    Convert to datetime using to_datetime, and then use isin to get your mask:

    dates = pd.to_datetime([date(2017, 7, 4), date(2016, 7, 4), ...])
    df['isholiday'] = df['date'].isin(dates)