Reputation: 607
Here is my data frame
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
This will produce:
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
I want to get the number of unique receipts per day.
Heres what I did:
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
I'm confused with this kind of index presentation so i reset it.
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
Now I grouped it by Date then showing only the Receipt count.
df2.groupby(['Date'])['Receipt'].count()
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
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?
Upvotes: 4
Views: 2997
Reputation: 210812
try this:
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
or this, depending on your goal:
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
Upvotes: 4