Python 如何选择具有日期时间索引和loc的两组年份?

Python 如何选择具有日期时间索引和loc的两组年份?,python,pandas,datetime,slice,multi-index,Python,Pandas,Datetime,Slice,Multi Index,我目前正在处理一个数十万行和更多行的数据帧,其中包含一个由日期时间值生成的索引 您可以使用以下代码创建my dataframe的微型示例: 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

我目前正在处理一个数十万行和更多行的数据帧,其中包含一个由日期时间值生成的索引

您可以使用以下代码创建my dataframe的微型示例:

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
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[(切片(无),['2015',2016'])]#仅在一年内首次工作,而不是列出年份

我认为您需要使用提取年份和过滤方式:

对于
多索引
解决方案类似,仅添加:

df1 = df[df.index.year.isin([2015, 2016])]
print (df1)
                     Value
Date                      
2015-01-01 00:00:00    858
2015-01-01 01:00:00    807
2015-01-01 02:00:00    895
2015-01-01 03:00:00    159
2015-01-01 04:00:00    176
                   ...
2016-12-31 19:00:00    888
2016-12-31 20:00:00    162
2016-12-31 21:00:00    207
2016-12-31 22:00:00    545
2016-12-31 23:00:00     49

[17544 rows x 1 columns]
df2 = mlti_df[mlti_df.index.get_level_values('Date').year.isin([2015, 2016])]
print (df2)
                          Value
lvl0 Date                      
a    2015-01-01 00:00:00    626
     2015-01-01 01:00:00    941
     2015-01-01 02:00:00    405
     2015-01-01 03:00:00    249
     2015-01-01 04:00:00    320
                        ...
b    2016-12-31 19:00:00    752
     2016-12-31 20:00:00    829
     2016-12-31 21:00:00    843
     2016-12-31 22:00:00    306
     2016-12-31 23:00:00     96

[35088 rows x 1 columns]