在Pandas多索引中选择日期范围的正确方法是什么?

时间:2018-04-27 23:45:31

标签: python pandas datetime time-series multi-index

在Pandas多索引中选择日期范围的正确方法是什么?

我有一个多索引数据框,如下所示:

enter image description here

如果我想选择某一天,使用xs就可以轻而易举:

data.xs('2011-11-11', level='Date').head()

但是,如果我想选择日期范围,我不能。以下所有内容都给出了Invalid Syntax错误:

data.xs('2011-10-10':'2011-11-11', level='Date').head()
data.xs(['2011-10-10':'2011-11-11'], level='Date').head()

注意#1 :我正在寻找一种使用优雅Pandas功能的方法。当然,使用4行或5行代码解决问题很容易,问题在于"正确的方式"是

注意#2 :我已经看过this answer,但这并没有涵盖这种情况。

1 个答案:

答案 0 :(得分:2)

使用上一个问题的数据:

d = {'Col1': {(Timestamp('2015-05-14 00:00:00'), '10'): 81.370003,
  (Timestamp('2015-05-14 00:00:00'), '11'): 80.41999799999999,
  (Timestamp('2015-05-14 00:00:00'), 'C3'): 80.879997,
  (Timestamp('2015-05-19 00:00:00'), '3'): 80.629997,
  (Timestamp('2015-05-19 00:00:00'), 'S9'): 80.550003,
  (Timestamp('2015-05-21 00:00:00'), '19'): 80.480003,
  (Timestamp('2015-05-22 00:00:00'), 'C3'): 80.540001},
 'Col2': {(Timestamp('2015-05-14 00:00:00'), '10'): 6.11282,
  (Timestamp('2015-05-14 00:00:00'), '11'): 6.0338,
  (Timestamp('2015-05-14 00:00:00'), 'C3'): 6.00746,
  (Timestamp('2015-05-19 00:00:00'), '3'): 6.10465,
  (Timestamp('2015-05-19 00:00:00'), 'S9'): 6.1437,
  (Timestamp('2015-05-21 00:00:00'), '19'): 6.16096,
  (Timestamp('2015-05-22 00:00:00'), 'C3'): 6.1391599999999995},
 'Col3': {(Timestamp('2015-05-14 00:00:00'), '10'): 39.753,
  (Timestamp('2015-05-14 00:00:00'), '11'): 39.289,
  (Timestamp('2015-05-14 00:00:00'), 'C3'): 41.248999999999995,
  (Timestamp('2015-05-19 00:00:00'), '3'): 41.047,
  (Timestamp('2015-05-19 00:00:00'), 'S9'): 41.636,
  (Timestamp('2015-05-21 00:00:00'), '19'): 42.137,
  (Timestamp('2015-05-22 00:00:00'), 'C3'): 42.178999999999995},
 'Col4': {(Timestamp('2015-05-14 00:00:00'), '10'): 44.950001,
  (Timestamp('2015-05-14 00:00:00'), '11'): 44.75,
  (Timestamp('2015-05-14 00:00:00'), 'C3'): 44.360001000000004,
  (Timestamp('2015-05-19 00:00:00'), '3'): 40.98,
  (Timestamp('2015-05-19 00:00:00'), 'S9'): 42.790001000000004,
  (Timestamp('2015-05-21 00:00:00'), '19'): 43.68,
  (Timestamp('2015-05-22 00:00:00'), 'C3'): 43.490002000000004}}

df = pd.Dataframe(d)

然后您可以使用partial string indexing选择日期范围:

df.loc['2015-05-14':'2015-05-19']

输出:

                    Col1     Col2    Col3       Col4
2015-05-14 10  81.370003  6.11282  39.753  44.950001
           11  80.419998  6.03380  39.289  44.750000
           C3  80.879997  6.00746  41.249  44.360001
2015-05-19 3   80.629997  6.10465  41.047  40.980000
           S9  80.550003  6.14370  41.636  42.790001