在numpy,Python中,当我想要设置的值是在不同大小的数组中时,如何有条件地重写数组的一部分?

Jec*_*cke 3 python arrays numpy

假设我有三个数组:

A[size1] of {0..size1}
B[size2] of {0..size1}
C[size2] of boolean
Run Code Online (Sandbox Code Playgroud)

我想要的是:

for (int e = 0; e < size2; ++e) :
    if C[e] == some_condition, then B[e] = A[B[e]]
Run Code Online (Sandbox Code Playgroud)

由于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]]
Run Code Online (Sandbox Code Playgroud)

Div*_*kar 5

你可以简单地使用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
Run Code Online (Sandbox Code Playgroud)