[英]Numpy add with multiple arrays
Is there a way to add (as opposed to sum) multiple arrays together in a single operation?有没有办法在一次操作中将多个 arrays相加(而不是求和)? Obviously, np.sum
and np.add
are different operations, however, the problem I'm struggling with right now is that np.add
only takes two arrays at once.显然, np.sum
和np.add
是不同的操作,但是,我现在正在努力解决的问题是np.add
一次只需要两个 arrays 。 I could utilize either我可以利用
output = 0
for arr in arr_list:
output = output + array
or或者
output = 0
for arr in arr_list:
output = np.add(output, array)
and, yes, this is workable.是的,这是可行的。 However, it would be nice if I could simply do some variant of但是,如果我可以简单地做一些变体就好了
output = np.add_multiple(arr_list)
Does this exist?这存在吗?
EDIT: I failed to be clear initially.编辑:我最初没有说清楚。 I specifically require a function that does not require an array of arrays to be constructed, as my arrays are not of equal dimensions and require broadcasting, for example:我特别需要一个 function ,它不需要构建一个 arrays数组,因为我的 arrays 尺寸不相等,需要广播,例如:
a = np.arange(3).reshape(1,3)
b = np.arange(9).reshape(3,3)
a, b = a[:,:,None,None], b[None,None,:,:]
These work:这些工作:
a + b # Works
np.add(a, b) # Works
These do not , and fail with the same exception:这些没有,并且失败并出现相同的异常:
np.sum([a, b], axis = 0)
np.add.reduce([a, b])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not broadcast input array from shape (3,1,1) into shape (1)
In [18]: alist = [np.arange(4),np.ones(4),np.array([10,1,11,2])]
In [19]: np.add.reduce(alist)
Out[19]: array([11., 3., 14., 6.])
In [20]: alist[0]+alist[1]+alist[2]
Out[20]: array([11., 3., 14., 6.])
And for more fun:为了获得更多乐趣:
In [21]: np.add.accumulate(alist)
Out[21]:
array([[ 0., 1., 2., 3.],
[ 1., 2., 3., 4.],
[11., 3., 14., 6.]])
edit编辑
In [53]: a.shape
Out[53]: (1, 1, 1, 3)
In [54]: b.shape
Out[54]: (3, 3, 1, 1)
Addition with broadcasting:添加广播:
In [63]: sum([a,b]).shape
Out[63]: (3, 3, 1, 3)
In [64]: (a+b).shape
Out[64]: (3, 3, 1, 3)
In [66]: np.add.reduce([a,b]).shape
Out[66]: (3, 3, 1, 3)
For what it's worth, I was suggesting add.reduce
because I thought you wanted to add more than 2 arrays.对于它的价值,我建议add.reduce
因为我认为您想添加超过 2 个 arrays。
All these work as long as the arrays broadcast together.所有这些工作只要 arrays 一起广播。
You can just use the Python's sum
built-in:您可以只使用 Python 的sum
内置:
output = sum(arr_list)
For many other numpy
functions, np.<ufunc>.reduce
can be used as shown by @hpaulj.对于许多其他numpy
函数,可以使用np.<ufunc>.reduce
.reduce,如 @hpaulj 所示。
You can use the sum()
to add multiple arrays.您可以使用sum()
添加多个 arrays。
arr = np.array([[6,2,3,5,4,3],
[7,7,2,4,6,7],
[10,6,2,4,5,9]])
np.add(0, arr.sum(axis=0))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.