3

I have a dataframe in the following format.

              1            2           3           4  
Data                                                                            
2001-07-30      0.363354   27.428261   14.639130   6.763423         
...                  ...         ...         ...        ...           
2015-06-15      0.039085   28.562948   14.000722   8.605911         

I wish to slice by month. Thus for example I want to select only data from month 5 and store this in a new variable. I have found several answers to similar questions. These however do not provide the intended result.

Examples of questions and answers in this area:

  1. Pandas DataFrame slicing by day/hour/minute
  2. python pandas dataframe slicing by date conditions
  3. pandas, python - how to select specific times in timeseries

I am new to timeseries analysis with Python and Pandas so any push to the right direction or reading material will be appreciated.

Community
  • 1
  • 1
Jelmer
  • 43
  • 1
  • 8

1 Answers1

6

datetimeindex has the attribute month to access and you can use this to filter the df:

In [132]:
df = pd.DataFrame(index=pd.date_range(dt.datetime(2015,1,1), dt.datetime(2015,5,1)))
df.loc[df.index.month==2]

Out[132]:
Empty DataFrame
Columns: []
Index: [2015-02-01 00:00:00, 2015-02-02 00:00:00, 2015-02-03 00:00:00, 2015-02-04 00:00:00, 2015-02-05 00:00:00, 2015-02-06 00:00:00, 2015-02-07 00:00:00, 2015-02-08 00:00:00, 2015-02-09 00:00:00, 2015-02-10 00:00:00, 2015-02-11 00:00:00, 2015-02-12 00:00:00, 2015-02-13 00:00:00, 2015-02-14 00:00:00, 2015-02-15 00:00:00, 2015-02-16 00:00:00, 2015-02-17 00:00:00, 2015-02-18 00:00:00, 2015-02-19 00:00:00, 2015-02-20 00:00:00, 2015-02-21 00:00:00, 2015-02-22 00:00:00, 2015-02-23 00:00:00, 2015-02-24 00:00:00, 2015-02-25 00:00:00, 2015-02-26 00:00:00, 2015-02-27 00:00:00, 2015-02-28 00:00:00]

Month indexing is 1 based so 5 would be May

EdChum
  • 376,765
  • 198
  • 813
  • 562