我知道这个解决方案
How to make a pandas crosstab with percentages?
,但建议的解决方案不适用于
三向桌
.
考虑下表:
df = pd.DataFrame({'A' : ['one', 'one', 'two', 'three'] * 6,
'B' : ['A', 'B', 'C'] * 8,
'C' : ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 4})
pd.crosstab(df.A,[df.B,df.C],colnames=['topgroup','bottomgroup'])
Out[89]:
topgroup A B C
bottomgroup bar foo bar foo bar foo
A
one 2 2 2 2 2 2
three 2 0 0 2 2 0
two 0 2 2 0 0 2
在这里,我想得到每个顶级组中的行百分比(
A、 B和C
).
使用
apply(lambda x: x/sum(),axis=1)
将失败,因为百分比的总和必须为1
在内部
每组。
有什么想法吗?