2016-07-14 47 views
2

可以说我有几个x-y对数组。我想创建一个新的数组,它以下列方式组合数据:结合数组对的高效方法?

新的x数组包含x数组中的所有x值(只有一次) 新的y数组包含y阵列中相应x值相同的所有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 

任何想法?

回答

2

我们可以用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.])