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

问题描述

我从现有的数据帧中得到了一个 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,1,0]

我不知道如何使用这种类型的数据索引,我搜索了多种工具来使用 DateTimeIndex,但找不到与解决我的案例相关的内容。范围应该与 DateTimeIndex(以秒为单位)精确,还是粗略猜测仍然有效?例如,“2020-06-25 11:00:00”到“2020-06-25 12:00:00”

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

解决方法

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

# 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,1])

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