gpt4 book ai didi

python - 如何按列累加numpy数组中的值?

转载 作者:太空宇宙 更新时间:2023-11-03 15:11:37 26 4
gpt4 key购买 nike

我如何使用 numpy accumulatoradd函数按列添加数组以制作基本累加器?

   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]

numpy 词汇表说 sum along axis argument axis=1 对行求和:“我们可以对数组的每一行求和,在这种情况下,我们沿着列或轴 1 进行操作”。

“二维数组有两个对应的轴:第一个垂直向下跨行(轴 0),第二个水平跨列(轴 1)”

使用 axis=1 我希望输出 [3,6,9],但这也会返回 [1,2,3].

当然可以!x 和 y 都不是二维的。

我做错了什么?

我可以手动使用 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]

最佳答案

我觉得

two_dim.sum(axis=0)
# [6 6 6]

会给你你想要的。

我不认为 accumulate 是您要找的东西,因为它提供了一个正在运行的操作,因此,使用 add 它看起来像:

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]

关于python - 如何按列累加numpy数组中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25880335/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com