[英]Pandas pivot_table to calculate share of margin
我有一個名為df
的Pandas
DataFrame
,其中包含n
columns
。 其中一columns
名為COUNT
,它顯示A
值出現了多少次。 A
包含唯一標識符,因此column
COUNT
中的每一行都具有值1
。 它看起來像這樣:
A B C D E COUNT
id1 cat1 1 a 15 1
id2 cat2 2 b 14 1
id3 cat2 2 c 14 1
id4 cat1 1 d 15 1
id5 cat3 2 e 14 1
.....
現在我想將我的df
轉換為如下所示:
14 15
cat1_tot NaN 2
cat1_share NaN 1
cat2_tot 2 NaN
cat2_share 0.6666 NaN
cat3_tot 1 NaN
cat3_share 0.3333 NaN
All 3 2
我可以catx_tot
使用pd.pivot_table
pd.pivot_table(
df,
values='COUNT',
index=['B'],
columns=['E'],
margins=True,
aggfunc=np.sum
)
但是我如何添加共享呢?
結合groupby.size
和groupby.transform
size = df.groupby(['B', 'E']).size()
sums = size.groupby(level='E').transform(np.sum)
aggd = pd.concat([size, size / sums], axis=1, keys=['total', 'share'])
aggd.unstack().stack(0)
獲取All
行
all_ = aggd.groupby(level='E').sum().total.rename(('All', 'total'))
aggd.unstack().stack(0).append(all_)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.