Suppose I have the following DataFrame:
import numpy as np
import pandas as pd
import datetime
index = pd.date_range(start=pd.Timestamp("2020/01/01 08:00"),
end=pd.Timestamp("2020/04/01 17:00"), freq='5T')
data = {'A': np.random.rand(len(index)),
'B': np.random.rand(len(index))}
df = pd.DataFrame(data, index=index)
It is easy to access every 8am say with the following command:
eight_am = df.loc[datetime.time(8,0)]
Suppose now I wish to access every 8am and every 9am. One way I could do this is via two masks:
mask1 = (df.index.time == datetime.time(8,0))
mask2 = (df.index.time == datetime.time(9,0))
eight_or_nine = df.loc[mask1 | mask2]
However, my issue comes with wanting to access many different different times of day. Say I wish to specify these times in a list say
times_to_access = [datetime.time(hr, mins) for hr, mins in zip([8,9,13,17],[0,15,35,0])]
It is quite ugly to create a mask variable for each time. Is there a nice way to do this programmatically in a loop, or perhaps there is a way of accessing multiple datetime.time
's that I am not seeing?