我使用numpy
做一些計算。在下面的代碼中:numpy array slicing避免for循環
assert(len(A.shape) == 2) # A is a 2D nparray
d1, d2 = A.shape
# want to initial G,which has the same dimension as A. And assign the last column of A to the last column of G
# initial with value 0
G = zero_likes(A)
# assign the last column to that of G
G[:, d2-1] = A[:, d2-1]
# the columns[0,dw-1] of G is the average of columns [0, dw-1] of A, based on the condition of B
for iW in range(d2-1):
n = 0
sum = 0.0
for i in range(d1):
if B[i, 0] != iW and B[i, 1] == 0:
sum += A[i, iW]
n += 1
for i in range(d1):
if B[i, 0] != iW and B[i, 1] == 0:
G[i, iW] = sum/(1.0 * n)
return G
是否有更簡單的方法使用「切片」或「布爾數組」?
謝謝!如果您想G
具有相同的維數爲A
,然後更改的G
適當元素
這將節省一些時間,以饗讀者,如果你情境你的代碼,說的是它的目的。另外/另外,你可以評論你的代碼。 – Antonio 2015-04-02 14:51:38
數組「A」是三維的嗎?否則'G = A [:,d2-1]'和'G [i,iw] = ...'沒有意義。但是,如果這是真的,'sum'也是一個一維數組,這是沒有意義的。請首先修正你顯示的代碼中的錯誤...你的意思是'G = A [:,:d2-1]'? – plonser 2015-04-02 15:21:19
給我們一個工作樣本! – hpaulj 2015-04-02 16:04:26