无for循环的numpy数组求和

时间:2019-05-16 05:48:43

标签: python

我有一个3D numpy(例如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,:,:])

.......  等等... 最后,B应该是3D数组,其每一帧都应按上述方法计算。

所以我要计算不带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).

能请你帮我吗

1 个答案:

答案 0 :(得分:0)

您可以使用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