1

My df dataset look likes this:

time                    Open
2017-01-03 07:00:00     5.2475
2017-01-04 08:00:00     5.2180
2017-01-05 09:00:00     5.2128
2017-01-02 07:00:00     5.4122
2017-01-03 08:00:00     5.2123
2017-01-04 09:00:00     5.2475
2017-01-01 07:00:00     5.2180
2017-01-02 08:00:00     5.2128
2017-01-03 09:00:00     5.4122
....

I have a list of Date like this:

# date_list could be of any size
date_list =['2017-01-05', '2017-01-03', '2017-01-12']

What I want to do is copy the next 2 rows of values starting from '07:00:00' time that matches the date_list including the first value to next 2 rows.

Basically, it has to copy from the date_list date and copy next 2 values with time starting from '07:00:00'

My new df will look like this:

time                    Open
2017-01-05 07:00:00     5.2475
2017-01-06 08:00:00     5.2180
2017-01-03 07:00:00     5.4122
2017-01-04 08:00:00     5.2123
2017-01-12 07:00:00     5.2180
2017-01-13 08:00:00     5.2128

Here, we are ordering the new df per the date_list that is a subset of the original df with only Date values from the date_list

What did I do?

I used df.index.isin(date_list) to find the date, but my original df has time values. I also do not know how to get the next 2 values.

Can you please help me?

floss
  • 2,603
  • 2
  • 20
  • 37

1 Answers1

0

You can combine this answer with between_time, as long as your index is a DatetimeIndex.

import pandas as pd

# dummy data
date_range = pd.date_range('2017-01-03 07:00:00', '2019-01-31', freq='60T')
df = pd.DataFrame(
    np.random.randint(1, 20, (date_range.shape[0], 1)),
    index=date_range, columns=['Open'])

date_list =['2017-01-05', '2017-01-03', '2017-01-12']

df[df.index.to_series().dt.date.astype(str).isin(date_list)].between_time('07:00', '08:00')

Gives

                     Open
2017-01-03 07:00:00     2
2017-01-03 08:00:00    13
2017-01-05 07:00:00     6
2017-01-05 08:00:00     2
2017-01-12 07:00:00     8
2017-01-12 08:00:00    11
Chris
  • 1,287
  • 12
  • 31