How to groupby time series data
<p>I have a dataframe below,column B's dtype is datetime64.</p>

<pre><code>    A      B
0   a   2016-09-13
1   b   2016-09-14
2   b   2016-09-15
3   a   2016-10-13
4   a   2016-10-14
</code></pre>

<p>I would like to groupby according to month(or in general year and day...)</p>

<p>so I would like to get count result  below, key = column B. </p>

<pre><code>              a       b
2016-09       1       2
2016-10       2       0
</code></pre>

<p>I tried groupby. but I couldn't figure out how to handle dtypes like datetime64... 
How can I handle and group dtype datetime64?</p>

<p>Say you start with</p>

<pre><code>In [247]: df = pd.DataFrame({'A': ['a', 'b', 'b', 'a', 'a'], 'B': ['2016-09-13', '2016-09-14', '2016-09-15', '2016-10-13', '2016-10-14']})

In [248]: df.B = pd.to_datetime(df.B)
</code></pre>

<p>Then you can <code>groupby</code>-<code>size</code>, then <code>unstack</code>:</p>

<pre><code>In [249]: df = df.groupby([df.B.dt.year.astype(str) + '-' + df.B.dt.month.astype(str), df.A]).size().unstack().fillna(0).astype(int)
</code></pre>

<p>Finally, you just need to make <code>B</code> a date again:</p>

<pre><code>In [250]: df.index = pd.to_datetime(df.index)

In [251]: df
Out[251]: 
A           a  b
B               
2016-10-01  2  0
2016-09-01  1  2
</code></pre>

<p>Note that the final conversion to a date-time set a uniform day (you can't have a "dayless" object of this type).</p>

python pandas