如何在多索引数据框架上过滤日期

时间:2017-07-03 01:33:26

标签: python pandas multi-index

我正在寻找一种过滤星期几和/或选定日期的多指数数据帧的方法。假设我需要

  • 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 ;
  • 最后是一个查询,将基于星期几和日期列表的选择组合在一起,例如Set<String> set; public void initialize(URL url, ResourceBundle rb){ set = new TreeSet<String>(): } @FXML public Set<String> addValue (MouseEvent e) throws IOException { Stage stage = new Stage (); root = FXMLoader.load(getClass).getResources(2ndFXML.fxml); stage.initModality(Modality.APPLICATION_MODAL); stage.iniOwner(clickedButton.getScene().getWindow(); stage.showAndWait(): return set; }

这样做的方法是什么?

@FXML
public void addSelection (MouseEvent e) throws IOException {
if (event.getSource() == button){
   stage = (Stage) button.getScene().getWindow();
   set.addAll(listSelection)
   stage.close
}

1 个答案:

答案 0 :(得分:5)

如果您的Date类型为datetime,则可以使用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