Conditional statements on numpy arrays

I have three huge numpy.arrays, and need to execute some conditional statements involving all three numpy.arrays fast. All numpy.arrays are of the same dimension (NxD)(N>2 and D>1) and of same datatype. Normally I would do as shown below

 for i in range(n):
     for j in range(d):
         if np.sign(nabla[i][j]) != np.sign(delta[i][j]):
             g[i][j] = g[i][j] + 0.2
         if np.sign(nabla[i][j]) == np.sign(delta[i][j]):
             g[i][j] = g[i][j] * 0.8

if I only had to operate with one numpy.array I would do

g[g < val] = newval

But I am receiving an error by applying the same principles since delta and nabla are more than two-dimensional.


You should consider using Boolean Indexing instead, e.g.:

mask = np.sign(nabla) == np.sign(delta)
g[mask] *= 0.8
g[~mask] += 0.2

Or alternatively:

g = np.where(np.sign(nabla) == np.sign(delta), g * 0.8, g + 0.2)

Leave a Reply

Your email address will not be published. Required fields are marked *