简体   繁体   English

不带for循环的numpy数组求和

[英]numpy array summation without a for loop

I have a 3D numpy(say A) array and want to make this operation without a for loop: 我有一个3D numpy(say A)数组,并希望在没有for循环的情况下进行此操作:

B[0,:,:]=Sum(A,axis=0)-(A[0,:,:])
B[1,:,:]=Sum(A,axis=0)-(A[0,:,:]+A[1,:,:])
B[2,:,:]=Sum(A,axis=0)-(A[0,:,:]+A[1,:,:]+A[2,:,:])

....... and so on... finally B should be a 3D array, each frame of it should be calculated as above. .......依此类推...最后B应该是一个3D数组,它的每一帧都应按上述方法计算。

So I want to calculate B without a for loop. 所以我想计算不带for循环的B。

Sum(A,axis=0) is easy to calculate but the problem in implementing the second term of B without for loop and also append the result to the B(3D array).

could you please help me 请你帮助我好吗

You can use np.cumsum : 您可以使用np.cumsum

# To make it easier to write for me, I am going to call you matrix "A": a, and "B": b

a_sum = np.sum(a, axis=0)
a_sum = a_sum[np.newaxis]
a_sum = np.repeat(a_sum, len(b), axis=0)

b = a_sum

a_cumsum = np.cumsum(a, axis=0)
b -= a_cumsum

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

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