如何在三向 table 中使用 pandas 交叉表获取行百分比?

How to get row percentages with pandas crosstab in a three-way table?

我知道这个解决方案 How to make a pandas crosstab with percentages?,但是建议的解决方案不适用于 三向 tables.

考虑以下 table:

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

有什么想法吗?

如果我理解你的问题,你似乎可以这样写:

>>> table = pd.crosstab(df.A,[df.B,df.C], colnames=['topgroup','bottomgroup'])
>>> table / table.sum(axis=1, level=0)

topgroup       A         B         C     
bottomgroup  bar  foo  bar  foo  bar  foo
A                                        
one          0.5  0.5  0.5  0.5  0.5  0.5
three        1.0  0.0  0.0  1.0  1.0  0.0
two          0.0  1.0  1.0  0.0  0.0  1.0