Search code examples
pandasnumpydatetimeindex

Create a list which values based on existing DateTimeIndex


I got a DateTimeIndex from an existing Dataframe

time=df.index[19:]

With a certain range of time, I want to create a certain value

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)

So in the result it should result something like below, that in certain time frame, the value will be 1 and other time frame it's just 0.

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

I don't know how to work with this type of data index and I have search multiple tools to work with DateTimeIndex but cannot find something related to solve my case. And should the range be something exact from the DateTimeIndex (in second), or something roughly guess is still gonna work? For example, '2020-06-25 11:00:00' to '2020-06-25 12:00:00'

Thank you so much for any help! Self-learning is not easy that sometime I don't even know what keyword should I look for.


Solution

  • You can check if the index is greater than the start of the range and less than the end of the range, apply & between them and convert to integers with 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)
    

    Output:

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

    P.S. In pandas it's better to avoid explicit loops wherever you can use vectorized operations instead, because it often affects performance materially