I'm trying to do the following with pandas. Counting item by state then expressing that number as a percentage of the subtotal. My dataframe has the raw data. I can get the counts but how to append another column for the percentages?
state_grp = df.groupby(by=['date', 'state','ad_type'])
state_grp.ad_type.agg(['count'])
I've wrote some sql which will do the same thing but how to do it in 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