Python,Pandas:将DateTimeIndex与Period进行比较的布尔索引 [英] Python, Pandas: Boolean Indexing Comparing DateTimeIndex to Period

查看:188
本文介绍了Python,Pandas:将DateTimeIndex与Period进行比较的布尔索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑一个数据框,该数据框在2010年1月的每一天每天包含1行,每行包含2个值:

Let's consider a DataFrame that contains 1 row of 2 values per each day of the month of Jan 2010:

date_range = pd.date_range(dt(2010,1,1), dt(2010,1,31), freq='1D')
df = pd.DataFrame(data = np.random.rand(len(date_range),2), index = date_range)

我想使用Period Period('2009-12-28/2010-01-03', 'W-SUN')创建一个布尔索引器,该索引器将返回仅包含那个Period的DataFrame.如何创建这样的布尔索引器? -理想情况下,无需将时间段转换为日期时间范围.

I would like to use the Period Period('2009-12-28/2010-01-03', 'W-SUN') to create a boolean indexer that would return a DataFrame containing only from that Period. How can I create such a boolean indexer? - Ideally without resorting to converting the period to a datetime range.

推荐答案

让查询pd.Period对象为:

query = pd.Period('2009-12-28/2010-01-03', 'W-SUN')

您可以通过访问其start_timeend_time属性直接通过以下方式进行操作:

You can do this directly in the following ways by accessing it's start_time and end_time attributes:

1)使用 DF.truncate :

1) Using DF.truncate:

df.truncate(query.start_time, query.end_time)

2)使用布尔索引器:

2) Using Boolean Indexer:

df[(df.index >= query.start_time) & (df.index <= query.end_time)]

3)使用默认包含两个端点的DateTime索引:

3) Using DateTime Indexing which by default includes both the endpoints:

df[query.start_time:query.end_time]

所有这些产生

这篇关于Python,Pandas:将DateTimeIndex与Period进行比较的布尔索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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