Group a list of dates by month, year
<pre><code>raw_data = ["2015-12-31", "2015-12-1" , "2015-1-1",
            "2014-12-31", "2014-12-1" , "2014-1-1",
            "2013-12-31", "2013-12-1" , "2013-1-1",]
expected_grouped_bymonth = [("2015-12", #dates_in_the_list_occured_in_december_2015)
                            , ...
                            ("2013-1",  #january2013dates)]
</code></pre>

<p>OR as a dict</p>

<pre><code>expected_grouped_bymonth = {
    "2015-12": #dates_in_the_list_occured_in_december_2015) , ...
    "2013-1", #january2013dates)}
</code></pre>

<p>I have a list of strings that represent dates. What I would like to have is a list of tuples, or a dictionary, that count per year or month the number of occurrences. What I've tried to do is something related to the <code>groupby</code>. I'm not able to understand how to use the the <code>TimeGrouper</code> according to the <code>groupby</code> function.</p>

<p>The raised exception is:</p>

<pre class="lang-none prettyprint-override"><code>TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex,
           but got an instance of 'RangeIndex'

from itertools import groupby
for el in data:
    if 'Real rates - Real volatilities' in el['scenario']:
        counter += 1
        real_records_dates.append(pd.to_datetime(el['refDate']))
print("Thera are {} real records.".format(counter))

BY_YEAR = 'Y'
BY_MONTH = 'M'
BY_DAY = 'D'

real_records_df = pd.DataFrame(pd.Series(real_records_dates))

real_records_df.groupby(pd.TimeGrouper(freq=BY_MONTH))
</code></pre>

<p>(You can also assume to start with a dictionary og <code>{date1:1, date2:2, ...}</code> if it easier. My problem is related only to the <code>groupby</code>.)</p>

<p>If you want to get the frequency of how often a date occurs per month and year you can use a <em>defaulftdict</em>:</p>

<pre><code>raw_data = ["2015-12-31", "2015-12-1", "2015-1-1",
        "2014-12-31", "2014-12-1", "2014-1-1",
        "2013-12-31", "2013-12-1", "2013-1-1",
        ]

from collections import defaultdict

dates = defaultdict(lambda:defaultdict(int))

for s in raw_data:
    k, v = s.rsplit("-", 1)
    dates[k][v] += 1

print(dates)
</code></pre>

<p>Or if you just want to <em>Group a list of dates by month, year</em>:</p>

<pre><code>dates = defaultdict(list)

for s in raw_data:
    k, v = s.rsplit("-", 1)
    dates[k].append(v)

print(dates)
</code></pre>

python list datetime pandas group-by