Making a list of months and years from DatetimeIndex in Pandas

jenryb picture jenryb · Jul 29, 2015 · Viewed 14.2k times · Source

I have a dataframe of information. I set the index to be the received date and time. Now I want a list

I set the df index doing this:

df.index = pd.to_datetime(df.index, format='%m/%d/%Y %H:%M')

which gives me this:

print df.index
<class 'pandas.tseries.index.DatetimeIndex'>
[2014-07-28 09:42:08, ..., 2015-07-28 09:06:12]
Length: 15177, Freq: None, Timezone: None

I want a list of the month and years in order to use them to plot, like so: ["Jan 2015", "Feb 2015", "Mar 2015", "Apr 2015", "May 2015", "June 2015", "Jul 2015", "Aug 2014", "Sep 2014", "Oct 2014", "Nov 2014", "Dec 2014"]

How can I do this? I've looked into something like this:

df = [datetime.datetime.strftime(n,'%b-%Y') for n in pd.DataFrame(df).resample('M').index] 

But this gives me the error DataError: No numeric types to aggregate.

Answer

EdChum picture EdChum · Jul 29, 2015

Original answer

The following should work: convert your datetimeindex to a series, so you can call apply and use strftime to return an array of strings:

In [27]:
import datetime as dt
import pandas as pd
df = pd.DataFrame(index=pd.date_range(start = dt.datetime(2014,1,1), end = dt.datetime.now(), freq='M'))
df.index.to_series().apply(lambda x: dt.datetime.strftime(x, '%b %Y'))

Out[27]:
2014-01-31    Jan 2014
2014-02-28    Feb 2014
2014-03-31    Mar 2014
2014-04-30    Apr 2014
2014-05-31    May 2014
2014-06-30    Jun 2014
2014-07-31    Jul 2014
2014-08-31    Aug 2014
2014-09-30    Sep 2014
2014-10-31    Oct 2014
2014-11-30    Nov 2014
2014-12-31    Dec 2014
2015-01-31    Jan 2015
2015-02-28    Feb 2015
2015-03-31    Mar 2015
2015-04-30    Apr 2015
2015-05-31    May 2015
2015-06-30    Jun 2015
Freq: M, dtype: object

If you want a list then just call tolist():

df.index.to_series().apply(lambda x: dt.datetime.strftime(x, '%b %Y')).tolist()

Updated answer

Actually, looking at this question 2 years later, I realise the above is completely unnecessary. You can just do:

In [10]:
df.index.strftime('%Y-%b')

Out[10]:
array(['2014-Jan', '2014-Feb', '2014-Mar', '2014-Apr', '2014-May',
       '2014-Jun', '2014-Jul', '2014-Aug', '2014-Sep', '2014-Oct',
       '2014-Nov', '2014-Dec', '2015-Jan', '2015-Feb', '2015-Mar',
       '2015-Apr', '2015-May', '2015-Jun', '2015-Jul', '2015-Aug',
       '2015-Sep', '2015-Oct', '2015-Nov', '2015-Dec', '2016-Jan',
       '2016-Feb', '2016-Mar', '2016-Apr', '2016-May', '2016-Jun',
       '2016-Jul', '2016-Aug', '2016-Sep', '2016-Oct', '2016-Nov',
       '2016-Dec', '2017-Jan', '2017-Feb', '2017-Mar', '2017-Apr',
       '2017-May', '2017-Jun', '2017-Jul'], 
      dtype='<U8')

datetimeindex support .dt accessors directly without converting to a Series