python - how to calculate a 2D array with numpy mask -


i have 2 dimension array , based if value greater 0 want operation (example x+1). in plain python this:

a = [[2,5], [4,0], [0,2]] x in range(3):     y in range(2):         if a[x][y] > 0:             a[x][y] = a[x][y] + 1  

result [[3, 6], [5, 0], [0, 3]]. want.

now want prevent nested loop , tried numpy this:

a = np.array([[2,5], [4,0], [0,2]]) mask = (a > 0) a[mask] + 1 

the result 1 dimension , shape of array [3 6 5 3]. how can operation , don't loose dimension in plain python example before?

if a numpy array, can -

a[a>0] +=1 

sample run -

in [335]: = np.array([[2,5], [4,0], [0,2]])  in [336]: out[336]:  array([[2, 5],        [4, 0],        [0, 2]])  in [337]: a[a>0] +=1  in [338]: out[338]:  array([[3, 6],        [5, 0],        [0, 3]]) 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -