pandas 根据模式生成日期序列

pandas generate a sequence of dates according to a pattern

我有这个日期序列,我想根据 3-2 模式创建一个带有标记的列:连续 3 天标记,然后 2 天不标记等。

import pandas as pd
date_pattern = pd.date_range(start='2020-01-01', end='2020-06-30')
date_pattern = pd.DataFrame({"my_date": date_pattern})
date_pattern

想要一个 'flag' 列,例如 1 代表 1 月 1 日到 03 日,然后是 1 月 6 日到 08 日,等等。

您可以对索引值使用模 5,然后比较 less like 3 每第四行和第五行:

date_pattern['flag'] = date_pattern.index % 5 < 3
#alternative for not default index
#date_pattern['flag'] = np.arange(len(date_pattern)) % 5 < 3
print(date_pattern.head(15))
      my_date   flag
0  2020-01-01   True
1  2020-01-02   True
2  2020-01-03   True
3  2020-01-04  False
4  2020-01-05  False
5  2020-01-06   True
6  2020-01-07   True
7  2020-01-08   True
8  2020-01-09  False
9  2020-01-10  False
10 2020-01-11   True
11 2020-01-12   True
12 2020-01-13   True
13 2020-01-14  False
14 2020-01-15  False