Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter specifc months from Pandas datetime index

I have a daily dataset which ranges from 2000-2010. I already set the column 'GregDate' via

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

as index. Now I only want to investigate the months from November till March (for all the ten years).

My dataframe looks like this:

                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]

I already had a look at this question, but I still am not able to solve my problem.

like image 576
user7448207 Avatar asked Dec 02 '22 12:12

user7448207


2 Answers

I think you need boolean indexing with DatetimeIndex.month and 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
like image 83
jezrael Avatar answered Jan 16 '23 00:01

jezrael


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
like image 36
MaxU - stop WAR against UA Avatar answered Jan 16 '23 01:01

MaxU - stop WAR against UA