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>If you set the index to the datetime you can use pd.TimeGrouper to sort by various time ranges. Example code:</p>

<pre><code># recreate dataframe
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']})
df['B'] = pd.to_datetime(df['B'])

# set column B as index for use of TimeGrouper
df.set_index('B', inplace=True)

# Now do the magic of Ami Tavory's answer combined with timeGrouper:
df = df.groupby([pd.TimeGrouper('M'), 'A']).size().unstack().fillna(0)
</code></pre>

<p>This returns:</p>

<pre><code>A             a    b
B                   
2016-09-30  1.0  2.0
2016-10-31  2.0  0.0
</code></pre>

<p>or alternatively (credits to ayhan) skip the setting to index step and use the following one-liner straight after creating the dataframe:</p>

<pre><code># recreate dataframe
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']})
df['B'] = pd.to_datetime(df['B'])
df = df.groupby([pd.Grouper(key='B', freq='M'), 'A']).size().unstack().fillna(0)
</code></pre>

<p>which returns the same answer</p>

python pandas