3

I have a numpy 2D array of size 3600 * 7200. I have another array of same shape which I want to use as a mask.

The problem is that when I do something like this:

import numpy as np
N = 10
arr_a = np.random.random((N,N))
arr_b = np.random.random((N,N))
arr_a[arr_b > 0.0]

The resulting array is no longer 2D, it is 1D. How do I get a 2D array in return?

2
  • How do you want to fill the values that are not greater than 0? With nan? If you don't fill them what kind of a shape are you expecting? What if only one of them is greater than 0? Commented May 12, 2016 at 5:13
  • thanks ayhan, nan would be ok to use for filling Commented May 12, 2016 at 5:16

1 Answer 1

2

You can use np.where to preserve the shape:

np.where(arr_b > 0.0, arr_a, np.nan)

It will take the corresponding values from arr_a when arr_b's value is greater than 0, otherwise it will use np.nan.

import numpy as np
N = 5
arr_a = np.random.randn(N,N)
arr_b = np.random.randn(N,N)
np.where(arr_b > 0.0, arr_a, np.nan)

Out[107]: 
array([[ 0.5743081 ,         nan, -1.69559034,         nan,  0.4987268 ],
       [ 0.33038264,         nan, -0.27151598,         nan, -0.73145628],
       [        nan,  0.46741932,  0.61225086,         nan,  1.08327459],
       [        nan, -1.20244926,  1.5834266 , -0.04675223, -1.14904974],
       [        nan,  1.20307104, -0.86777899,         nan,         nan]])
Sign up to request clarification or add additional context in comments.

Comments

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.