创建一个列表,其中的值基于现有的 DateTimeIndex

Create a list which values based on existing DateTimeIndex

我从现有的 Dataframe 中获得了 DateTimeIndex

time=df.index[19:]

在一定的时间范围内,我想创造一定的价值

list=[]
for i in range(0,len(time)):
    #if time[i] in the range of '2020-06-25 11:53:05' to '2020-06-25 12:23:05': this part I don't know how
        correct.append(1)
    else:
        correct.append(0)

所以在结果中它应该像下面这样,在特定的时间范围内,该值将为 1,而在其他时间范围内它仅为 0。

list= [0,0,0,0,1,1,1,0,0,0,0]

我不知道如何使用这种类型的数据索引,我已经搜索了多种工具来使用 DateTimeIndex,但找不到与解决我的案例相关的东西。并且该范围应该与 DateTimeIndex(以秒为单位)完全一致,还是粗略猜测仍然有效?例如,'2020-06-25 11:00:00' 到 '2020-06-25 12:00:00'

非常感谢您的帮助!自学不易,有时甚至不知道该找什么关键词。

您可以检查索引是否大于范围的开始和小于范围的结束,在它们之间应用 & 并使用 astype(int):[=15 转换为整数=]

# create sample index
time = pd.DatetimeIndex(
    pd.date_range('2020-06-25 11:00:00', '2020-06-25 12:15:00', freq='10min'))

# check if time within certain ranges
z = ((time > '2020-06-25 11:53:05') & (time < '2020-06-25 12:23:05'))
z |= ((time > '2020-06-25 10:00:00') & (time < '2020-06-25 11:20:00'))

z.astype(int)

输出:

array([1, 1, 0, 0, 0, 0, 1, 1])

P.S。在 pandas 中,最好避免在任何可以使用矢量化操作的地方使用显式循环,因为它通常会严重影响性能