考虑使用交叉表的margins,将这三个元素连接成一个df。下面用你的例子:newdf = pd.concat([pd.crosstab(df.A, df.B, margins=True),
pd.crosstab(df.A, df.B).apply(lambda r: r/r.sum(), axis=0),
pd.crosstab(df.A, df.B).apply(lambda r: r/r.sum(), axis=1)])
newdf = newdf.loc[['one','two','three','All']] # RE-ORDER INDEX VALUES
newdf = newdf[['A', 'B', 'C', 'All']] # RE-ORDER COLUMNS
newdf['All'] = np.where(pd.isnull(newdf['All']) & # ROW PERCENTAGES SUM
(newdf['A'] + newdf['B'] + newdf['C']==1),
1, newdf['All'])
print(newdf)
# A B C All
# A
# one 4.000000 4.000000 4.000000 12.0
# one 0.500000 0.500000 0.500000 NaN
# one 0.333333 0.333333 0.333333 1.0
# two 2.000000 2.000000 2.000000 6.0
# two 0.250000 0.250000 0.250000 NaN
# two 0.333333 0.333333 0.333333 1.0
# three 2.000000 2.000000 2.000000 6.0
# three 0.250000 0.250000 0.250000 NaN
# three 0.333333 0.333333 0.333333 1.0
# All 8.000000 8.000000 8.000000 24.0