【问题标题】:Create multiple OR conditions within loop for use in .loc with datetime.time在循环中创建多个 OR 条件以在 .loc 中与 datetime.time 一起使用
【发布时间】:2020-04-24 17:15:44
【问题描述】:

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

【问题讨论】:

  • df.iloc[np.isin(df.index.time,times_to_access)] 做到了。谢谢

标签: python pandas python-datetime


【解决方案1】:

np.in1dboolean 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]

将索引转换为Series 是可能的,但我认为如果大DataFrame 会更慢:

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

【讨论】:

  • 谢谢,这行得通。虽然当 DataFrame 的大小很大时它不是最快的,但我觉得这很奇怪,因为我认为 numpy 实现很快
猜你喜欢
  • 1970-01-01
  • 2013-12-12
  • 2020-12-23
  • 2021-07-25
  • 1970-01-01
  • 2022-07-25
  • 2013-09-20
  • 2019-04-20
  • 2018-07-20
相关资源
最近更新 更多