首页 > 解决方案 > 在循环中创建多个 OR 条件以在 .loc 中与 datetime.time 一起使用

问题描述

假设我有以下数据框:

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我没有看到的?

标签: pythonpandaspython-datetime

解决方案


np.in1d与 一起使用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)]

推荐阅读