指示行的日期时间是否在日期范围内

Indicate whether datetime of row is in a daterange

我正在尝试获取数据集中假期的虚拟变量。我有几个带假期的日期范围 (pd.daterange()) 和一个数据框,我想在其中附加一个虚拟对象以指示该行的日期时间是否在指定假期的某个日期范围内。

小例子:

ChristmasBreak = list(pd.date_range('2014-12-20','2015-01-04').date)

dates = pd.date_range('2015-01-03', '2015-01-06, freq='H')
d = {'Date': dates, 'Number': np.rand(len(dates))}

df = pd.DataFrame(data=d)
df.set_index('Date', inplace=True)

for i, row in df.iterrows():
    if i in ChristmasBreak:
        df[i,'Christmas] = 1

从未输入 if loop,因此无法匹配日期。有什么办法吗?也欢迎使用其他方法来模拟这种情况!

首先不要使用iterrows,因为really slow.

最好使用 dt.date with Series,isin,最后将布尔掩码转换为整数 - Trues 是 1:

df = pd.DataFrame(data=d)

df['Christmas'] = df['Date'].dt.date.isin(ChristmasBreak).astype(int)

或使用between:

df['Christmas'] = df['Date'].between('2014-12-20', '2015-01-04').astype(int)

如果要与DatetimeIndex比较:

df = pd.DataFrame(data=d)
df.set_index('Date', inplace=True)

df['Christmas'] = df.index.date.isin(ChristmasBreak).astype(int)

df['Christmas'] = ((df.index > '2014-12-20') & (df.index < '2015-01-04')).astype(int)

示例:

ChristmasBreak = pd.date_range('2014-12-20','2015-01-04').date

dates = pd.date_range('2014-12-19 20:00', '2014-12-20 05:00', freq='H')
d = {'Date': dates, 'Number': np.random.randint(10, size=len(dates))}

df = pd.DataFrame(data=d)

df['Christmas'] = df['Date'].dt.date.isin(ChristmasBreak).astype(int)
print (df)
                 Date  Number  Christmas
0 2014-12-19 20:00:00       6          0
1 2014-12-19 21:00:00       7          0
2 2014-12-19 22:00:00       0          0
3 2014-12-19 23:00:00       9          0
4 2014-12-20 00:00:00       1          1
5 2014-12-20 01:00:00       3          1
6 2014-12-20 02:00:00       1          1
7 2014-12-20 03:00:00       8          1
8 2014-12-20 04:00:00       2          1
9 2014-12-20 05:00:00       1          1

这应该可以满足您的要求:

df['Christmas'] = df.index.isin(ChristmasBreak).astype(int)