在循环内创建多个 OR 条件以在 .loc 中使用 datetime.time

Create multiple OR conditions within loop for use in .loc with datetime.time

假设我有以下 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)

使用以下命令很容易访问每早上 8 点说:

eight_am = df.loc[datetime.time(8,0)]

假设现在我希望每早上 8 点和每 9 点访问一次。我可以做到这一点的一种方法是通过两个掩码:

mask1 = (df.index.time == datetime.time(8,0))
mask2 = (df.index.time == datetime.time(9,0))

eight_or_nine = df.loc[mask1 | mask2]

但是,我的问题是想要访问一天中的许多不同时间。说我想在列表中指定这些时间说

times_to_access = [datetime.time(hr, mins) for hr, mins in zip([8,9,13,17],[0,15,35,0])]

每次都创建一个掩码变量,非常难看。有没有一种在循环中以编程方式执行此操作的好方法,或者也许有一种方法可以访问我没有看到的多个 datetime.time

使用np.in1d with boolean indexing:

df = df[np.in1d(df.index.time, times_to_access)]
print (df)
                            A         B
2020-01-01 08:00:00  0.904687  0.922797
2020-01-01 09:15:00  0.467908  0.457840
2020-01-01 13:35:00  0.747596  0.534620
2020-01-01 17:00:00  0.559217  0.283298
2020-01-02 08:00:00  0.546884  0.361523
                      ...       ...
2020-03-31 17:00:00  0.541345  0.289005
2020-04-01 08:00:00  0.734592  0.137986
2020-04-01 09:15:00  0.108603  0.955305
2020-04-01 13:35:00  0.109969  0.187756
2020-04-01 17:00:00  0.222852  0.125966

[368 rows x 2 columns]

Pandas 只有将索引转换为 Series 的解决方案是可能的,但我认为如果大型 DataFrame 会更慢:

df = df[df.index.to_series().dt.time.isin(times_to_access)]