[Python] How to use numpy masked arrays to create a masked xarray DataArray

Discussão em 'Python' iniciado por Stack, Março 5, 2025.

  1. Stack

    Stack Membro Participativo

    I'm new to stackexchange, so I'm sorry if I make any mistakes in posting here.

    I'm using metpy.calc.windchill in order to calculate wind chill values, and it automatically spits out an array with a numpy mask on it.

    wind_chill = metpy.calc.windchill(
    t2m * units.K,
    wind_mag * units('m/s'),
    )

    windchill_ma = wind_chill.to_masked_array()
    mask = ma.getmask(windchill_ma)


    The mask is a numpy ndarray with boolean values.

    I'd like to convert all values that are masked (set as True in the mask) to np.nan while retaining the DataArray structure.

    For example:

    wind_chill = xr.DataArray(array([[[1,6,4,8],[2,4,3,5]],[[2,5,3,6],[2,6,4,8]]]))
    mask = array([[[True,True,False,False],[........

    masked_wind_chill = xr.DataArray(array([[[NaN,NaN,4,8......



    masked_wind_chill = wind_chill.where(~mask)



    and other variations of .where(mask=False) and whatnot just end up not applying the mask at all to the data. If I use .where(mask=True), all data points are masked regardless of if the value is True or False for that data point. Am I using mask wrong?

    Thank you for reading!

    Continue reading...

Compartilhe esta Página