簡體   English   中英

熊貓groupby數量和占總數的比例

[英]pandas groupby count and proportion of group total

我正在嘗試對熊貓做以下事情。 然后按州計算項目,然后將該數字表示為小計的百分比。 我的數據框包含原始數據。 我可以得到計數,但是如何在百分比后面添加另一列?

state_grp = df.groupby(by=['date', 'state','ad_type'])
state_grp.ad_type.agg(['count'])

在此處輸入圖片說明

我寫了一些sql,它會做同樣的事情,但是如何在pandas中做呢?

with cte1 as
(
    select distinct date, state, ad_type, count(ad_type) over (partition by date, state, ad_type) as [# of Ads]
    from propertylistings
),

cte2 as
(
    select *, sum([# of Ads]) over (partition by state) as subtotal
    from dhg
)

select date, state, ad_type, [# of Ads], round(cast([# of Ads] as float)/cast(subtotal as float) * 100, 1) as [%]
from cte2
order by date, state, ad_type

在此處輸入圖片說明

你可以用transform + sum

state_grp = df.groupby(by=['date', 'state','ad_type'])
state_grp=state_grp.ad_type.agg(['count'])
state_grp['%']=state_grp['count']/state_grp.groupby(level=[0,1])['count'].transform('sum')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM