让我们考虑一个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
更多推荐
发布评论