Counting values using pandas groupby
<p>Here is my data frame</p>

<pre><code>data = {'Date' : ['08/20/10','08/20/10','08/20/10','08/21/10','08/22/10','08/24/10','08/25/10','08/26/10'] , 'Receipt' : [10001,10001,10002,10002,10003,10004,10004,10004],
   'Product' : ['xx1','xx2','yy1','fff4','gggg4','fsf4','gggh5','hhhg6']}

dfTest = pd.DataFrame(data)
dfTest
</code></pre>

<p>This will produce:</p>

<pre><code>    Date    Product    Receipt
0   08/20/10    xx1    10001
1   08/20/10    xx2    10001
2   08/20/10    yy1    10002
3   08/21/10    fff4    10002
4   08/22/10    gggg4   10003
5   08/24/10    fsf4    10004
6   08/25/10    gggh5   10004
7   08/26/10    hhhg6   10004
</code></pre>

<p>I want to get the number of unique receipts per day.</p>

<p>Heres what I did:</p>

<pre><code>dfTest.groupby(['Date','Receipt']).count()

                  Product
Date    Receipt 
08/20/10    10001   2
            10002   1
08/21/10    10002   1
08/22/10    10003   1
08/24/10    10004   1
08/25/10    10004   1
08/26/10    10004   1
</code></pre>

<p>I'm confused with this kind of index presentation so i reset it.</p>

<pre><code>df2 = dfTest.groupby(['Date','Receipt']).count().reset_index()
df2

    Date    Receipt   Product
0   08/20/10    10001   2
1   08/20/10    10002   1
2   08/21/10    10002   1
3   08/22/10    10003   1
4   08/24/10    10004   1
5   08/25/10    10004   1
6   08/26/10    10004   1
</code></pre>

<p>Now I grouped it by Date then showing only the Receipt count.</p>

<p>df2.groupby(['Date'])['Receipt'].count()</p>

<pre><code>Date
08/20/10    2
08/21/10    1
08/22/10    1
08/24/10    1
08/25/10    1
08/26/10    1
Name: Receipt, dtype: int64
</code></pre>

<p>There I got the number of unique receipts per day. I'm thinking the way I came up with my solution is a bit crude. Is there a better way of doing what I intend to do?</p>

<p>try this:</p>

<pre><code>In [191]: dfTest.groupby('Date').Receipt.nunique()
Out[191]:
Date
08/20/10    2
08/21/10    1
08/22/10    1
08/24/10    1
08/25/10    1
08/26/10    1
Name: Receipt, dtype: int64
</code></pre>

<p>or this, depending on your goal:</p>

<pre><code>In [188]: dfTest.groupby(['Date','Receipt']).Product.nunique().reset_index(level=1, drop=True)
Out[188]:
Date
08/20/10    2
08/20/10    1
08/21/10    1
08/22/10    1
08/24/10    1
08/25/10    1
08/26/10    1
Name: Product, dtype: int64
</code></pre>

python pandas dataframe group-by