【问题标题】:Efficient way to combine pairs of arrays?组合成对数组的有效方法?
【发布时间】:2016-07-15 17:40:05
【问题描述】:

假设我有几个 x-y- 对数组。我想创建一对以以下方式组合数据的新数组:

新的 x 数组包含 x 数组中的所有 x 值(仅一次) 新的 y 数组包含对应的 x 值相同的 y 数组中所有 y 值的总和。例如。

x1 = np.array([0, 1, 2, 3])
y1 = np.array([3, 2, 5, 7])

x2 = np.array([0, 2, 3, 4, 5])
y2 = np.array([4, 5, 4, 1, 6])

x3 = np.array([-2, -1, 0])
y3 = np.array([1, 0, 1])

a = np.array([x1, x2, x3])
b = np.array([y1, y2, y3])

x, y = array_combiner(a, b)

>>> x
array([-2, -1, 0, 1, 2,  3,  4, 5])
>>> y
array([ 1,  0, 8, 2, 10, 11, 1, 6])   #sum from previous arrays from corresponding x-values

有什么想法吗?

【问题讨论】:

    标签: arrays numpy


    【解决方案1】:

    我们可以使用np.uniquenp.bincount,就像这样-

    # Collect all x-arrays and y-arrays into 1D arrays each
    X = np.concatenate((x1,x2,x3))
    Y = np.concatenate((y1,y2,y3))
    
    # Get unique X elems & tag each X element based on its uniqueness among others
    Xout,tag = np.unique(X,return_inverse=True)
    
    # Use tags to perform tagged summation of Y elements
    Yout = np.bincount(tag,Y)
    

    样本输出 -

    In [64]: Xout
    Out[64]: array([-2, -1,  0,  1,  2,  3,  4,  5])
    
    In [65]: Yout
    Out[65]: array([  1.,   0.,   8.,   2.,  10.,  11.,   1.,   6.])
    

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 1970-01-01
      • 2013-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-17
      • 2022-01-18
      相关资源
      最近更新 更多