0

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.

mylearning
  • 65
  • 6

1 Answers1

1

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

perl
  • 9,826
  • 1
  • 10
  • 22
  • May I ask why we need "freq='10min' "? Thank you so much! – mylearning May 06 '21 at 12:31
  • I'm just creating a sample data here, which you won't need of course if you already have a DataFrame with DateTimeIndex. The choice of `10min` specifically is arbitrary, I wanted there to be not too many values, but both values within the range and outside of it, so I can test that values within the range produce 1s and those outside the range produce 0s – perl May 06 '21 at 12:40
  • Oh yes I understand it now! Could you also suggest a solution if I have more than 1 range? Unfortunately, I have just checked with 2 ranges inside 'time' but it could only work with 1 range – mylearning May 06 '21 at 12:48
  • @mylearning Sure, updated my answer for 2 ranges, please see if it helps – perl May 06 '21 at 12:51
  • 1
    "|=" is new for me, thanks! I've learned a lot from you – mylearning May 06 '21 at 12:54