【发布时间】:2016-09-29 15:24:58
【问题描述】:
我有一个名为 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
我可以通过pd.pivot_table得到catx_tot
pd.pivot_table(
df,
values='COUNT',
index=['B'],
columns=['E'],
margins=True,
aggfunc=np.sum
)
但是我该如何添加分享呢?
【问题讨论】:
标签: python pandas pivot-table