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?
Я использую metpy.calc.windchill для расчета значений охлаждения ветра, и он автоматически выплевывает массив с маской Numpy. lon и время. < /p> [code]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')
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[/code], все значения, в том числе те, которые отмечены как -, существуют. В результате, когда я график этот временный шаг, все значения отображаются, даже те, которые предположительно должны быть замаскированы -. Такие методы, как .filled () и .fill_na () также не работают по этой причине. Когда я пытаюсь применить маску с помощью .to_masked_array () , маска также устанавливается на False для всех этих значений, помеченных как '-'. Есть ли способ найти значения, которые устанавливаются как - и создать маску, используя их, чтобы я мог установить их - отмеченные значения как NAN?
Мне нужно изменить очень большой файл geoTiff (более 200 ГБ), однако при его сохранении мой код дает сбой при загрузке файла в память. Код выглядит следующим образом.
import xarray as xr
Мне нужно изменить очень большой файл geoTiff (более 200 ГБ), однако при его сохранении мой код дает сбой при загрузке файла в память. Код выглядит следующим образом.
import xarray as xr
У меня есть xarray.DataArray, содержащий значения от 0 до 34. Массив является трехмерным, с измерениями времени (ежедневные данные за 30 лет), широты и lon определяет местоположение. Следует отметить, что для некоторых мест в широте и долготе все...
Я новичок в использовании библиотеки xarray, и у меня есть некоторые сомнения/вопросы.
У меня есть этот набор данных::
ds
Size: 2GB
Dimensions: (Latitude: 364, Longitude: 246, Lon_u: 247, Lat_v: 364,
Time: 1087)
Coordinates:
Longitude (Latitude,...