如何从Pandas datetime索引中过滤特定月份

时间:2017-07-27 13:33:52

标签: python python-3.x pandas datetime

我有一个每日数据集,范围从2000年到2010年。我已经设置了专栏' GregDate'通过

df.set_index(pd.DatetimeIndex(df['GregDate'])) 

作为索引。现在我只想调查从11月到3月的所有月份(十年来)。

我的数据框如下所示:

                Sigma        Lat        Lon
GregDate                                   
2000-01-01  -5.874062  79.913437 -74.583125
2000-01-02  -6.794000  79.904000 -74.604000
2000-01-03  -5.826061  79.923939 -74.548485
2000-01-04  -5.702439  79.916829 -74.641707
...
2009-07-11 -10.727381  79.925952 -74.660714
2009-07-12 -10.648000  79.923667 -74.557333
2009-07-13 -11.123095  79.908810 -74.596190

[3482 rows x 3 columns]

我已经看过这个question,但我仍然无法解决我的问题。

2 个答案:

答案 0 :(得分:4)

我认为boolean indexingDatetimeIndex.month需要Index.isin

df = df[df.index.month.isin([11,12,1,2,3])]
print (df)
               Sigma        Lat        Lon
GregDate                                  
2000-01-01 -5.874062  79.913437 -74.583125
2000-01-02 -6.794000  79.904000 -74.604000
2000-01-03 -5.826061  79.923939 -74.548485
2000-01-04 -5.702439  79.916829 -74.641707

答案 1 :(得分:4)

In [10]: df.query("index.dt.month in [11,12,1,2,3]")
Out[10]:
               Sigma        Lat        Lon
GregDate
2000-01-01 -5.874062  79.913437 -74.583125
2000-01-02 -6.794000  79.904000 -74.604000
2000-01-03 -5.826061  79.923939 -74.548485
2000-01-04 -5.702439  79.916829 -74.641707