假设我有三个数组:
A[size1] of {0..size1}
B[size2] of {0..size1}
C[size2] of boolean
我想要的是:
for (int e = 0; e < size2; ++e) :
if C[e] == some_condition, then B[e] = A[B[e]]
由于Python速度很慢,我必须通过数组上的numpy算法来实现它我该怎么做?
例子:
A = np.array([np.random.randint(0,n,size1), np.random.randint(0,size1,size1)])
B = np.random.randint(0,size1,size2)
C = np.random.randint(0,n,size2)
#that's the part I want to do in numpy:
for i in range (size2) :
if (C[i] > A[0][B[i]]) :
B[i] = A[1][B[i]]
最佳答案
您只需使用boolean-indexing
-
mask = C > A[0][B] # Create mask to select valid ones from B
B[mask] = A[1][B[mask]] # Use mask to select and assign values