user308827
user308827

Reputation: 22031

Subsetting 2D array based on condition in numpy python

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?

Upvotes: 3

Views: 2136

Answers (1)

user2285236
user2285236

Reputation:

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]])

Upvotes: 2

Related Questions