Search code examples
pythonpython-3.xnumpynumpy-ndarrayvalueerror

Error when masking 2d numpy array


I'm not sure what the correct terminology is here but I'm trying to mask out some values in a numpy array using multiple conditions from several arrays. For example, I want to find and mask out the areas in X where arrays t/l,lat2d,x, and m meet certain criteria. All the arrays are of the same shape: (250,500). I tried this:

cs[t < 274.0 | 
   l > 800.0 |
   lat2d > 60 |
   lat2d < -60 | 
   (x > 0 & m > 0.8) |
   (x < -25 & m < 0.2)] = np.nan

ufunc 'bitwise_and' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''.

I replaced the &,| with and/or and got the error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I've tried creating a mask: mask = t < 274.0 | l > 800.0 | lat2d > 60 | lat2d < -60 | (x > 0 & m > 0.8) | (x < -25 & m < 0.2), in order to use in a masked array but got the same error.

any idea how to do this in Python 3?


Solution

  • This is just a matter of operator precedence:

    cs[(t < 274.0) | 
       (l > 800.0) |
       (lat2d > 60) |
       (lat2d < -60) |
       ((x > 0) & (m > 0.8)) |
       ((x < -25) & (m < 0.2))] = np.nan
    

    should work