简体   繁体   中英

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, eg:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM