如何用日期时间索引和位置选择两组年份?

问题描述 投票:1回答:1

我目前正在处理数十万行及更多行的数据帧,并由日期时间值构成索引。

您可以使用以下代码创建我的数据框的微型示例:

import pandas as pd
import numpy as np

dates = pd.date_range(start='1/1/2015', end='1/1/2020', freq='H')
df = pd.DataFrame(dates, columns=['Date'])
df['Value'] = np.random.randint(0,1000, len(dates))
df.set_index('Date', inplace=True)

我想选择所有'2015'和2018'年,或'2015-01'和'2015-06'。我知道如何使用SliceIndex在两个值之间分割。我知道如何获得整整一年,但我不知道如何通过loc获得整整两年。

df['2015'] # it works
df[(slice('2015', '2016')] # or df['2015':'2016']

# but
df[['2015', '2016']] # it does not work.

实际上,我有一个多索引。建立一个例子:

df1 = df.copy()
df['lvl0'] = ['a']*len(df)
df1['lvl0'] = ['b']*len(df)
mlti_df = pd.concat([df, df1]).reset_index().set_index(['lvl0', 'Date'])

mlti_df[(slice(None), ['2015', '2016'])] # <= does not work

是否可以通过这种方式获得行?我昨天在几个小时内没有找到答案。

python pandas datetime slice multi-index
1个回答
1
投票

第一个partial string indexing仅使用一年,而不使用年份列表。

我认为您需要partial string indexing,其中Index.isin提取年份,并通过Index.isin过滤:

DatetimeIndex.year

并且对于DatetimeIndex.year解决方案是类似的,仅添加boolean indexing

boolean indexing
© www.soinside.com 2019 - 2024. All rights reserved.