Home > Mobile >  Trying to mask out certain values using np.where
Trying to mask out certain values using np.where

Time:09-17

I have a 3D array (can be thought of as time, y, and x), and I am trying to mask out values between .4 and .6 to show a contour plot with all values between .4 to .6 being in either white (or basically masked out).

arr_3d = np.random.rand(5,10,20)


plt.pcolormesh(arr_3d[2])
plt.colorbar()

example of contour plot at one time instance

Here is my attempt to mask out any values between .4 and .6:

# mask out or turn to zero values that are between .4 and .6

attempt_to_mask = np.where((arr_3d > .4) & (arr_3d < .6),arr_3d == 0)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/tmp/ipykernel_562130/1333698014.py in <module>
      7 # mask out or turn to zero values that are between .4 and .6
      8 
----> 9 attempt_to_mask = np.where((arr_3d > .4) & (arr_3d < .6),arr_3d == 0)

<__array_function__ internals> in where(*args, **kwargs)

ValueError: either both or neither of x and y should be given

What does the error mean? How might I mask out all values between .4 and .6 for each time step in the 3d array (size 5,10,20).

CodePudding user response:

May be you want to something like this?

arr_3d[(arr_3d > .4) & (arr_3d < .6)] = 0

Note: before applying the above code, you may need to make a copy of the original array.

CodePudding user response:

Just found another alternative (if you want them masked instead of turned to zeros):

masked = ma.masked_where((arr_3d > .4) & (arr_3d < .6), arr_3d)

Answer above also works well :)

  • Related