假设我有几个 x-y- 对数组。我想创建一对新的数组,通过以下方式组合数据:
新的 x 数组包含 x 数组中的所有 x 值(仅一次) 新的 y 数组包含 y 数组中所有 y 值的总和,其中对应的 x 值相同。例如。
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
有什么想法吗?
最佳答案
我们可以使用np.unique
和 np.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.])
关于arrays - 组合数组对的有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38384165/