我使用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