简体   繁体   English

(m, 2), (n, 2) 数组的有效相加

[英]efficient addition of (m, 2), (n, 2) arrays

I have two numpy arrays, x of shape (m, 2) and y of shape (n, 2) .我有两个numpy的阵列, x形状的(m, 2)y形状的(n, 2) I would like compute the (m, n, 2) array where at position (i, j) one finds the sum of x[i] and y[j] at out[i, j] .我想计算(m, n, 2)数组,其中在(i, j)位置找到x[i]y[j]out[i, j]的总和。 List comprehension works列表理解作业

import numpy

x = numpy.random.rand(13, 2)
y = numpy.random.rand(5, 2)

xy = numpy.array([
    [xx + yy for yy in y]
    for xx in x
])

but I was wondering if there is a more efficient solution via numpy.add.outer or something along those lines.但我想知道是否有通过numpy.add.outer或类似方法的更有效的解决方案。

You can use numpys broadcasting rules to cast the first array to the shape (13, 1, 2) and the second to the shape (1, 5, 2) :您可以使用 numpys 广播规则将第一个数组转换为形状(13, 1, 2) ,将第二个数组转换为形状(1, 5, 2)

numpy.all(x[:, None, :] + y[None, :, :] == xy)
# True

The array is repeated across the dimension where None is added (since it has length 1).该数组在添加None的维度上重复(因为它的长度为 1)。

Therefore the shape of the output becomes (13, 5, 2) .因此输出的形状变为(13, 5, 2)

xy = x[:, None]+y

应该做的伎俩。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM