# How to mask out the CONUS from a netcdf file and write it again into netcdf?

**URL:** https://discourse.pangeo.io/t/how-to-mask-out-the-conus-from-a-netcdf-file-and-write-it-again-into-netcdf/2520
**Category:** Data
**Created:** [June 11, 2022, 3:14pm UTC](https://discourse.pangeo.io/t/how-to-mask-out-the-conus-from-a-netcdf-file-and-write-it-again-into-netcdf/2520 "2022-06-11T15:14:22Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![alifallahm](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/alifallahm/32/1594_2.png) [@alifallahm](https://discourse.pangeo.io/u/alifallahm)
#### Post date: [June 11, 2022, 3:14pm UTC](https://discourse.pangeo.io/t/how-to-mask-out-the-conus-from-a-netcdf-file-and-write-it-again-into-netcdf/2520/1 "2022-06-11T15:14:22Z")

</div>

Hi,

Is there any efficient way to mask the Xarray’s datasets for a specific country and save that output for further analyses?

GeoCAT suggested two ways “cover” or “clip”. But the output is not suitable to save it as a netcdf file “.to\_netcdf”. It happens as the output is kind of raster.

[https://geocat-examples.readthedocs.io/en/latest/gallery/Overlays/NCL\_overlay\_11a.html#sphx-glr-gallery-overlays-ncl-overlay-11a-py](https://geocat-examples.readthedocs.io/en/latest/gallery/Overlays/NCL_overlay_11a.html#sphx-glr-gallery-overlays-ncl-overlay-11a-py)

Alternatives are suggested like : Geopandas.clip, rioxarray, salem, regionmask.

> <https://gist.github.com/shoyer/0eb96fa8ab683ef078eb>

> <https://github.com/pydata/xarray/issues/501>
>
> Can we set a shapefile as a mask for each netcdf file and run xray methods for v…alues within the shapefile region?
> 
> for example if I want to create a timeseries of monthly mean temperature for 'mystate' from a netcdf file that contains data for the whole country:
> 
> filepath = r"DATA/temp/\_/\_temp.nc"
> shapefile = r"DATA/mystate.shp"
> 
> ds=xray.open\_mfdataset(filepath) 
> ds\_variable=ds\['temp'\]
> monthlymean=ds\_variable.resample('1MS', dim='time', how='mean')
> meanmonthlyofmystate=monthlymean.groupby('time').mean() #add somewhere here the shapefile
> meanmonthlyofmystate.to\_pandas().plot()

Here we need to install different packages which take lots of time. I would appreciate any idea/link/example on more direct solution.

---

<div class="post-metadata">

### Author: ![alifallahm](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.pangeo.io/alifallahm/32/1594_2.png) [@alifallahm](https://discourse.pangeo.io/u/alifallahm)
#### Post date: [June 12, 2022, 6:21pm UTC](https://discourse.pangeo.io/t/how-to-mask-out-the-conus-from-a-netcdf-file-and-write-it-again-into-netcdf/2520/2 "2022-06-12T18:21:11Z")

</div>

Here I found the answer; one fantastic example using rioxarray which worked wonderfully!

> <https://gis.stackexchange.com/questions/382037/python-rioxarray-clip-masking-netcdf-data-with-a-polygon-returns-all-nan/433378#433378>
