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

Python 如何在三向表中使用pandas交叉表获取行百分比?,python,pandas,dataframe,percentage,crosstab,Python,Pandas,Dataframe,Percentage,Crosstab,我知道这个解决方案,但提出的解决方案不适用于三向表 考虑下表: 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],coln

我知道这个解决方案,但提出的解决方案不适用于三向表

考虑下表:

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
在这里,我想得到每个topgroup(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

这不就是ct/ct.sum(轴=1,级别=0)?其中,
ct
是您的
交叉表
在20秒前评论的完全相同,我认为这是正确的+1oh,这是纯粹的熊猫魔术。一旦我看到它,它现在看起来是如此明显。谢谢我认为你的想法对其他人很有用
level=0
是因为我的表是按列多索引的,对吗?谢谢EdChum@Noobie:没错,
axis=1
表示我们希望沿每行应用该操作,如果您有一个多索引,您可以传递一个
level
参数,将该方法应用于该多索引的特定级别。