简体   繁体   English

如何检查datetime值列是否在日期列表中?

[英]How to check if column of datetime values is in a 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. 我想在数据框中为新列分配true / false,以了解特定日期是否在列表中。 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. 上面总是错误的。

Convert to datetime using to_datetime , and then use isin to get your mask: 转换为datetime使用to_datetime ,然后用isin拿到你的面具:

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

You should try using datetime.datetime objects instead of datetime.date objects to construct your list of dates. 您应该尝试使用datetime.datetime对象而不是datetime.date对象来构造日期列表。 Your data types need to be equivalent. 您的数据类型必须相等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM