![](/img/trans.png)
[英]How do I group by two columns and then count the occurrences of each unique value in a third column for each of the groupings?
[英]Pandas group by two columns and count the second column value by each group
我有一個域數據集,有人可以告訴我如何使用 Pandas 過濾具有多個擴展名的域。
我按此代碼對其進行了分組,但得到了以下結果:
dfActive.groupby(['domain','ext'])['ext'].nunique()
結果:
domain com 1
sample com 1
mashhadmap com 1
net 1
預期結果:
mashhadmap 2
如果需要按sum
計算每個第一級domain
,IIUC 使用:
dfActive.groupby(['domain','ext'])['ext'].nunique().groupby(level=0).sum()
如果每個第一級重復,則需要過濾器值:
s = dfActive.groupby(['domain','ext'])['ext'].nunique()
s = s[s.index.get_level_values(0).duplicated(keep=False)]
#and then if need aggregate sum
out = s.groupby(level=0).sum()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.