arrays - 组合数组对的有效方法?

标签 arrays numpy

假设我有几个 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.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.])

关于arrays - 组合数组对的有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38384165/

相关文章:

PHP strpos 匹配大海捞针

arrays - flash as3 - 如何在数组中找到对象的索引

javascript - 谷歌地图不起作用,位置数组?

python - 我可以在数据帧的行之间执行操作吗?

python - 比较两个不同大小的一维数组中的元素,具有公差

char数组中的C++ Num到int

python - 在 for 循环中使用相应的 3D numpy 数组

python - np.sum 的 Numba nopython 错误

python - 如何使用 numpy 数组计算字母序列中的位置

python - 对值数组进行计算 - Python