Как использовать массивы Numpy Masked для создания Masked Xarray Dataarray?Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Как использовать массивы Numpy Masked для создания Masked Xarray Dataarray?

Сообщение Anonymous »

Я использую metpy.calc.windchill для расчета значений охлаждения ветра, и он автоматически выплевывает массив с маской Numpy. lon и время. < /p>

Код: Выделить всё

t2m = xr.open_dataarray('ERA5_t2m_hourly_2004_2024.nc')
vwind = xr.open_dataarray('ERA5_vwind_hourly_2004_2024.nc')
uwind = xr.open_dataarray('ERA5_uwind_hourly_2004_2024.nc')

def wind_tot(uwind, vwind):
wind_mag = np.sqrt(vwind**2 + uwind**2)
wind_dir = np.arctan2(vwind/wind_mag, uwind/wind_mag)
wind_dir = wind_dir * 180/np.pi

return wind_mag, wind_dir

wind_mag, wind_dir = wind_tot(uwind, vwind)

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)
< /code>
Маска представляет собой Numpy Ndarray с логическими значениями. < /p>
Я бы хотел преобразовать все значения, которые маскируются (устанавливаются как истинные в маске) ​​в np.nan, сохраняя структуру данных.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......
< /code>
masked_wind_chill = wind_chill.where(~mask)
< /code>
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?
Edit: Implementing arr.filled:
windchill_ma = wind_chill.to_masked_array()
masked_windchill = windchill_ma.filled(np.nan)

windchill_da = xr.DataArray(masked_windchill, coords={
'time':wind_chill.time,
'lat':wind_chill.lat,
'lon':wind_chill.lon,
})
windchill_da
< /code>
gives similar results. I found that the methods I'm using are working as intended, but the mask I have doesn't seem to correspond to the areas marked as '--' in the wind_chill dataset, which is what I would like to mask for, since they're above the necessary temperature and below the wind thresholds.
mask = ma.getmask(windchill_ma)
< /code>
returns an array full of 'False' at timesteps that are marked entirely as '--' by wind_chill, which in turn should be True in the mask, I think. Is the mask I'm using not correct?
Edit 2:
Looking at a specific time step:
enter image description here
I'd like to convert all values that are masked as '--' to np.nan while retaining the DataArray structure.
However, looking at the actual values using wind_chill.sel(time='2020-08-25 T12:00:00').values
, все значения, в том числе те, которые отмечены как -, существуют. В результате, когда я график этот временный шаг, все значения отображаются, даже те, которые предположительно должны быть замаскированы -. Такие методы, как .filled () и .fill_na () также не работают по этой причине. Когда я пытаюсь применить маску с помощью .to_masked_array () , маска также устанавливается на False для всех этих значений, помеченных как '-'. Есть ли способ найти значения, которые устанавливаются как - и создать маску, используя их, чтобы я мог установить их - отмеченные значения как NAN?

Подробнее здесь: https://stackoverflow.com/questions/794 ... -dataarray
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»