创建带有计数和百分比的列联表 Pandas

ibo*_*oru 8 python pivot-table crosstab pandas

有没有更好的方法可以使用 pd.crosstab() 或 pd.pivot_table() 在 Pandas 中创建列联表来生成计数百分比

当前解决方案

cat=['A','B','B','A','B','B','A','A','B','B']
target = [True,False,False,False,True,True,False,True,True,True]

import pandas as pd
df=pd.DataFrame({'cat' :cat,'target':target})
Run Code Online (Sandbox Code Playgroud)

使用交叉表

totals=pd.crosstab(df['cat'],df['target'],margins=True).reset_index()
percentages = pd.crosstab(df['cat'],
   df['target']).apply(lambda row: row/row.sum(),axis=1).reset_index()
Run Code Online (Sandbox Code Playgroud)

和合并

summaryTable=pd.merge(totals,percentages,on="cat")
summaryTable.columns=['cat','#False',
    '#True','All','percentTrue','percentFalse']
Run Code Online (Sandbox Code Playgroud)

输出

+---+-----+--------+-------+-----+-------------+--------------+
|   | cat | #False | #True | All | percentTrue | percentFalse |
+---+-----+--------+-------+-----+-------------+--------------+
| 0 | A   |      2 |     2 |   4 | 0.500000    | 0.500000     |
| 1 | B   |      2 |     4 |   6 | 0.333333    | 0.666667     |
+---+-----+--------+-------+-----+-------------+--------------+
Run Code Online (Sandbox Code Playgroud)

Max*_*axU 1

您可以执行以下操作:

In [131]: s = df.groupby('cat').agg({'target': ['sum', 'count']}).reset_index(level=0)

In [132]: s.columns
Out[132]:
MultiIndex(levels=[['target', 'cat'], ['sum', 'count', '']],
           labels=[[1, 0, 0], [2, 0, 1]])
Run Code Online (Sandbox Code Playgroud)

让我们对列名称进行排序:

In [133]: s.columns = [col[1] if col[1] else col[0] for col in s.columns.tolist()]

In [134]: s
Out[134]:
  cat  sum  count
0   A  2.0      4
1   B  4.0      6

In [135]: s['pctTrue'] = s['sum']/s['count']

In [136]: s['pctFalse'] = 1 - s.pctTrue

In [137]: s
Out[137]:
  cat  sum  count   pctTrue  pctFalse
0   A  2.0      4  0.500000  0.500000
1   B  4.0      6  0.666667  0.333333
Run Code Online (Sandbox Code Playgroud)