How to compute 2D array with numpy mask
I have a dimensional array and it is based if the value is greater than 0. I want to do an operation (example with x + 1). In simple 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 a 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 1 size and shape of the array [3 6 5 3]. How can I perform this operation and not lose the dimension like in the simple python example before?
+3
source to share