[英]Counting values using pandas groupby
這是我的數據框架
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
這將產生:
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
我想獲得每天唯一收據的數量。
繼承人我做了什么:
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
我對這種索引表示感到困惑,所以我重置它。
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
現在我按日期對其進行分組,然后僅顯示收據計數。
df2.groupby([ '日期'])[ '收據']。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
我在那里得到了每天唯一收據的數量。 我想我提出解決方案的方式有點粗糙。 有沒有更好的方式來做我打算做的事情?
試試這個:
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
或者這個,取決於你的目標:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.