how to calculate a 2D array with numpy mask

634 Views Asked by At

I have a 2 dimension array and based if the value is greater than 0 I want to do a operation (example with x+1). In plain python something like this:

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

Result for a is [[3, 6], [5, 0], [0, 3]]. This is what I want.

Now I want to prevent the nested loop and tried with numpy something like this:

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

The result is now a 1 dimension and the shape of the array [3 6 5 3]. How can I do this operation and don't loose the dimension like in the plain python example before?

1

There are 1 best solutions below

2
On BEST ANSWER

If a is a numpy array, you can simply do -

a[a>0] +=1

Sample run -

In [335]: a = np.array([[2,5], [4,0], [0,2]])

In [336]: a
Out[336]: 
array([[2, 5],
       [4, 0],
       [0, 2]])

In [337]: a[a>0] +=1

In [338]: a
Out[338]: 
array([[3, 6],
       [5, 0],
       [0, 3]])