Skip to content

Instantly share code, notes, and snippets.

@matteodefelice
Created March 28, 2025 20:35
Show Gist options
  • Select an option

  • Save matteodefelice/b7785206b6dff207e726fbb716064805 to your computer and use it in GitHub Desktop.

Select an option

Save matteodefelice/b7785206b6dff207e726fbb716064805 to your computer and use it in GitHub Desktop.
mask xarray using regionmask
# %%
import xarray as xr
import numpy as np
import geopandas as gpd
import regionmask
# %%
gd = xr.open_dataset("C:/Users/matte/data/tasmax_day_ACCESS-CM2_historical_r1i1p1f1_gn_1999.nc")
# gd.coords['lon'] = (gd.coords['lon'] + 180) % 360 - 180
# gd = gd.sortby(gd.lon)
# %%
counties = gpd.read_file("cb_2018_us_county_20m.shp").iloc[120:121].to_crs('4326')
# %%
mask_counties = regionmask.from_geopandas(
counties,
names = "GEOID",
abbrevs = "_from_name"
)
# %%
mask = mask_counties.mask(gd)
print(mask)
mask_co = gd.where(mask == 120)['tasmax'].dropna(dim = 'lat', how = 'all').dropna(dim = 'lon', how = 'all')
mask_co.isel(time = 0).plot()
# %%
mask_co_ts = mask_co.mean(dim = ['lat', 'lon'])
mask_co_ts.plot()
# %%
newlon = np.linspace(360 + counties.bounds['minx'].values[0], 360 + counties.bounds['maxx'].values[0], 20)
newlat = np.linspace(counties.bounds['miny'].values[0], counties.bounds['maxy'].values[0], 20)
gdinterp = gd.interp(lon=newlon, lat=newlat, method='linear')
# %% HIGHRES
mask = mask_counties.mask(gdinterp)
mask_co = gdinterp.where(mask == 120)['tasmax'].dropna(dim = 'lat', how = 'all').dropna(dim = 'lon', how = 'all')
mask_co.isel(time = 0).plot()
# %%
mask_co_ts = mask_co.mean(dim = ['lat', 'lon'])
mask_co_ts.plot()
# %%
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment