Python,Pandas:布尔索引将DateTimeIndex与Period进行比较(Python, Pandas: Boolean Indexing Comparing DateTimeIndex

编程入门 行业动态 更新时间:2024-10-24 15:22:58
Python,Pandas:布尔索引将DateTimeIndex与Period进行比较(Python, Pandas: Boolean Indexing Comparing DateTimeIndex to Period) python

让我们考虑一个DataFrame,它包含2010年1月每一天的1行2个值:

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。 我怎样才能创建这样的布尔索引器? - 理想情况下,无需将期间转换为日期时间范围。

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)

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_time和end_time属性,以下列方式直接执行此操作:

1)使用DF.truncate :

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

2)使用布尔索引器:

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

3)使用DateTime Indexing,默认情况下包括两个端点:

df[query.start_time:query.end_time]

所有这些产生

在此处输入图像描述

Let the query pd.Period object be:

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

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

1) Using DF.truncate:

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

2) Using Boolean Indexer:

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

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

df[query.start_time:query.end_time]

All these produce

enter image description here

更多推荐

本文发布于:2023-04-29 08:56:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1335952.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:布尔   索引   Python   Pandas   DateTimeIndex

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!