如何按列在numpy数组中累积值? [英] How to accumulate values in numpy array by column?
问题描述
如何使用numpy 累加器和 add 函数可以逐列添加数组以构成基本累加器?
How do I use the numpy accumulator and add functions to add arrays column wise to make a basic accumulator?
import numpy as np
a = np.array([1,1,1])
b = np.array([2,2,2])
c = np.array([3,3,3])
two_dim = np.array([a,b,c])
y = np.array([0,0,0])
for x in two_dim:
y = np.add.accumulate(x,axis=0,out=y)
return y
实际输出:[1,2,3]
所需的输出:[6,6,6]
actual output: [1,2,3]
desired output: [6,6,6]
numpy词汇表说沿轴的总和参数axis=1
对行求和:我们可以对数组的每一行求和,在这种情况下,我们将沿着列或轴1进行操作."
numpy glossary says the sum along axis argument axis=1
sums over rows: "we can sum each row of an array, in which case we operate along columns, or axis 1".
二维数组具有两个相应的轴:第一个二维数组在行上垂直向下(轴0),第二个数组在列上水平向下(轴1)"
对于axis=1
,我希望输出为[3,6,9]
,但这也会返回[1,2,3]
.
With axis=1
I would expect output [3,6,9]
, but this also returns [1,2,3]
.
当然! x和y都不是二维的.
Of Course! neither x nor y are two-dimensional.
我做错了什么?
我可以手动使用np.add()
aa = np.array([1,1,1])
bb = np.array([2,2,2])
cc = np.array([3,3,3])
yy = np.array([0,0,0])
l = np.add(aa,yy)
m = np.add(bb,l)
n = np.add(cc,m)
print n
现在我得到正确的输出,[6,6,6]
and now I get the correct output, [6,6,6]
推荐答案
我认为
two_dim.sum(axis=0)
# [6 6 6]
会给您您想要的东西.
我不认为accumulate
是您正在寻找的东西,因为它提供了运行中的操作,因此,使用add
它将看起来像:
I don't think accumulate
is what you're looking for as it provides a running operation, so, using add
it would look like:
np.add.accumulate(two_dim)
[[1 1 1]
[3 3 3] # = 1+2
[6 6 6]] # = 1+2+3
reduce
更像您所描述的:
np.add.reduce(two_dim)
[6 6 6]
这篇关于如何按列在numpy数组中累积值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!