检查 datetimeindex 是否属于另一个日期列表并应用条件

Checking if a datetimeindex falls into another list of dates and applying condition

使用 python,我创建了一个带有日期时间索引的数据框。

datetime_index = pd.date_range(start='2018-01-01', end='2019-12-31', freq='D')
df = pd.DataFrame({}, index=datetime_index)

现在我希望能够搜索日期列表,如果索引中的日期也在我创建的列表中,我想要一个新变量 df['fireworks'] 来为 1,否则为 0。 我试过创建这样的列表:

fireworks = {'2018-07-04', '2018-07-05', '2018-04-13', '2018-04-18'}

我试过这样做:

df['fireworks'] = np.where(df.index==fireworks, 1, 0)

新创建的df['fireworks']的所有值仍然是0。

提前感谢任何帮助我的人。

使用Series.isin:

datetime_index = pd.date_range(start='2018-01-01', end='2019-12-31', freq='D')
df = pd.DataFrame({}, index=datetime_index)

fireworks = {'2018-07-04', '2018-07-05', '2018-04-13', '2018-04-18'}

df['fireworks'] = np.where(df.index.isin(fireworks), 1, 0)

print (df[df["fireworks"].eq(1)])

#
            fireworks
2018-04-13          1
2018-04-18          1
2018-07-04          1
2018-07-05          1