3

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 Answer 1

2

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]])
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! With a mask it would be a[mask] = a[mask]+ 1 right?
@gustavgans Here a>0 is the mask. So it's equivalent to a[mask] += 1. That += is an in-situ change. Another more explicit way to put it would be as you did: a[mask] = a[mask]+ 1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.