如何在多索引数据框上过滤日期
问题内容:
我正在寻找一种方法来按星期几和/或选定的日期过滤多索引数据框,如下所示。假设我需要
- 查询
select only mondays
; - 我想要在另一个查询
select all days except monday and friday
; - 第三个查询,用于选择日期输入列表中的数据,例如
select all dates in ['2015-05-14', '2015-05-21', '2015-05-22']
; - 最后是一个结合了基于星期几的选择和日期列表(如)的查询
select all dates in ['2015-05-14', '2015-05-21', '2015-05-22'] and thursdays
。
怎么做呢?
Col1 Col2 Col3 Col4
Date Two
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
2015-05-21 19 80.480003 6.16096 42.137 43.680000
2015-05-22 C3 80.540001 6.13916 42.179 43.490002
问题答案:
如果具有Date
asdatetime
类型,则可以使用dayofweek
获取星期几并基于该日期进行查询。
仅选择星期一:
df[df.index.get_level_values('Date').dayofweek == 0]
选择星期一和星期五以外的日期:
import numpy as np
df[np.in1d(df.index.get_level_values('Date').dayofweek, [1,2,3,5,6])]
# Col1 Col2 Col3 Col4
# Date Two
#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
#2015-05-21 19 80.480003 6.16096 42.137 43.680000