Python:具有相同可能值的两列的计数频率

Python: counting frequency for two columns with the same possible values

我有两列 两个可能的值(0 或 1)。一列是预测值,另一列是实际值。像这样。

ID Predicted Real  
1   1        1  
2   1        0  
3   0        0  
4   0        1  
5   1        0  
6   1        0  

我想计算每列中 0 和 1 的频率。像这样

Value Predicted Real  
1      4         2  
0      2         4 

想用结果制作一个垂直条形图

您可以将 pd.value_counts 应用于数据框(假设 ID 是索引而不是列,如果不先将 ID 设置为索引)

out = df.apply(pd.value_counts).rename_axis('Value').reset_index()

   Value  Predicted  Real
0      0          2     4
1      1          4     2

df.apply(pd.value_counts).rename_axis('Value').plot(kind='bar') #customize as you want