Reputation: 21
Lets say I have several x- y- pairs of arrays. I want to create a new pair of arrays that combines the data in the following way:
The new x array contains all the x-values in the x- arrays (only once) The new y array contains the sum of all the y- values in the y- arrays where the corresponding x- values are the same. For instance.
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
Any ideas?
Upvotes: 2
Views: 147
Reputation: 221534
We can use np.unique
and np.bincount
, like so -
# 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)
Sample output -
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.])
Upvotes: 2