Skip to main content
 首页 » 编程设计

python之Pandas :计算两列之间匹配项的最佳方法

2025年05月04日21haluo1

我有一个像这样的数据框:

   actual  prediction 
0       1           0 
1       0           0 
2       0           0   
3       1           0  
4       1           1 
5       0           0 

是否有一种 pythonic 方式来获得类似于以下的结果:

number of (0, 0) = 3 
number of (0, 1) = 0 
number of (1, 0) = 2 
number of (1, 1) = 1 

我并不完全需要它,而且我有多个版本的代码可以实现这一点,但它似乎太冗长了。获得它的 pythonic 方法是什么?

请您参考如下方法:

Pandas 解决方案(与@Divakar 的紧凑型 Numpy 解决方案相比不是那么好):

from itertools import product 
 
In [291]: cats = ['{0[0]}{0[1]}'.format(tup) for tup in product([0,1], [0,1])] 
 
In [292]: pd.Categorical((df.actual.astype(str)+df.prediction.astype(str)), 
                         categories=cats) \ 
            .value_counts() 
Out[292]: 
00    3 
01    0 
10    2 
11    1 
dtype: int64 

如果您不需要像(0, 1)这样列出缺失的组合:

In [298]: df.groupby(df.columns.tolist()).size().reset_index() 
Out[298]: 
   actual  prediction  0 
0       0           0  3 
1       1           0  2 
2       1           1  1