【问题标题】:Pandas: Best way to count matches between two columns?熊猫:计算两列之间匹配的最佳方法?
【发布时间】:2017-04-27 14:10:34
【问题描述】:

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

   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方法是什么?

【问题讨论】:

    标签: python pandas numpy collections


    【解决方案1】:

    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
    

    【讨论】:

    • 哇,我期待你们大师提供一些基于groupby 的紧凑型解决方案!比如groupby,然后value_counts
    • @Divakar,我必须使用分类 dtype 才能获得 # 个缺失的组合,例如 (0, 1)
    【解决方案2】:

    如果我们正在处理0s1s,这是dot-product 的一种方式-

    np.bincount(df.dot([2,1]))
    

    【讨论】:

    • @nevabyte 这就是为什么在开头提到If 部分。
    • 在您编辑问题以反映这一点之前发表了我的评论
    【解决方案3】:

    添加自定义类别应该可以工作:

    df = pd.DataFrame({"actual":[0,0,0,1,2,3],"prediction":[0,0,1,2,15,14]})
    df['customCategory'] = (df.actual.apply(lambda x: str(x)+',')+df.prediction.astype(str))
    df.groupby('customCategory').customCategory.count()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-25
      • 2019-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多