【问题标题】:Calculate mean of array with specific value from another array计算具有来自另一个数组的特定值的数组的平均值
【发布时间】:2016-09-20 15:39:58
【问题描述】:

我有这些 numpy 数组:

array1 = np.array([-1, -1, 1, 1, 2, 1, 2, 2])
array2 = np.array([34.2, 11.2, 22.1, 78.2, 55.0, 66.87, 33.3, 11.56])

现在我想返回一个二维数组,其中 array1 的每个独特值都有平均值,所以我的输出看起来像这样:

array([[-1, 22.7],
       [ 1, 55.7],
       [ 2, 33.3]])

有没有将这些一维数组连接到一个二维数组的有效方法?谢谢!

【问题讨论】:

    标签: python arrays performance numpy


    【解决方案1】:

    这是一个典型的分组操作,numpy_indexed 包(免责声明:我是它的作者)提供了对 numpy 的扩展,以高效简洁地执行这些类型的操作:

    import numpy_indexed as npi
    groups, means = npi.group_by(array_1).mean(array_2)
    

    请注意,您也可以通过这种方式轻松执行其他类型的缩减,例如中位数。

    【讨论】:

      【解决方案2】:

      这是一种使用np.uniquenp.bincount 的方法-

      # Get unique array1 elems, tag them starting from 0 and get their tag counts
      unq,ids,count = np.unique(array1,return_inverse=True,return_counts=True)
      
      # Use the tags/IDs to perform ID based summation of array2 elems and 
      # thus divide by the ID counts to get ID based average values
      out = np.column_stack((unq,np.bincount(ids,array2)/count))
      

      示例运行 -

      In [16]: array1 = np.array([-1, -1, 1, 1, 2, 1, 2, 2])
          ...: array2 = np.array([34.2, 11.2, 22.1, 78.2, 55.0, 66.87, 33.3, 11.56])
          ...: 
      
      In [18]: out
      Out[18]: 
      array([[ -1.        ,  22.7       ],
             [  1.        ,  55.72333333],
             [  2.        ,  33.28666667]])
      

      【讨论】:

        猜你喜欢
        • 2014-05-14
        • 2013-10-25
        • 1970-01-01
        • 2021-12-16
        • 1970-01-01
        • 2014-10-13
        • 2019-04-08
        • 1970-01-01
        相关资源
        最近更新 更多