使用.loc访问器的 pandas 日期时间索引的布尔掩码 [英] Boolean mask from pandas datetime index using .loc accessor

查看:97
本文介绍了使用.loc访问器的 pandas 日期时间索引的布尔掩码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

总结以下玩具代码:

import numpy as np
import pandas as pd
rng = pd.date_range('1/1/2011', periods=72, freq='H')
avec = np.random.rand(len(rng))
bvec = np.random.rand(len(rng))
df = pd.DataFrame({"A":avec,"B":bvec}, index=rng)

我现在可以选择时间间隔的一部分

I can now select a part of the time interval with

df.loc["2011-01-02",:]

有没有一种方法可以有效地访问与所得切片对应的布尔掩码,即:

Is there a way to efficiently access the boolean mask that corresponds to the resulting slice, i.e:

array([False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False], dtype=bool)

我尝试了早期的stackoverflow答案中的建议,但需要很长时间才能在我的数据集上运行...

I have tried the suggestions in an earlier stackoverflow answer but df.index.date takes a very long time to run on my dataset...

推荐答案

如果性能很重要,请使用2个布尔值掩码:

If performance is important chain 2 boolean masks:

(df.index >= "2011-01-02") & (df.index < "2011-01-03")

这篇关于使用.loc访问器的 pandas 日期时间索引的布尔掩码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆