title: Python: using polygons to create a mask on a given 2d grid
body: <p>I have some <strong>polygons</strong> (Canadian provinces), read in with <code>GeoPandas</code>, and want to use these to create a mask to apply to gridded data on a 2-d latitude-longitude grid (read from a <em>netcdf</em> file using <code>iris</code>). An end goal would be to <em>only have data for a given province remaining, with the rest of the data masked out</em>. So the mask would be 1's for grid boxes within the province, and 0's or NaN's for grid boxes outside the province. </p>
  
  <hr>
  
  <p>The polygons can be obtained from the shapefile here: 
  <a href="https://www.dropbox.com/s/o5elu01fetwnobx/CAN_adm1.shp?dl=0" rel="nofollow noreferrer">https://www.dropbox.com/s/o5elu01fetwnobx/CAN_adm1.shp?dl=0</a></p>
  
  <p>The netcdf file I am using can be downloaded here: 
  <a href="https://www.dropbox.com/s/kxb2v2rq17m7lp7/t2m.20090815.nc?dl=0" rel="nofollow noreferrer">https://www.dropbox.com/s/kxb2v2rq17m7lp7/t2m.20090815.nc?dl=0</a></p>
  
  <hr>
  
  <p>I imagine there are two approaches here but I am struggling with both:</p>
  
  <p>1) Use the polygon to create a mask on the latitude-longitude grid so that this can be applied to lots of datafiles outside of python (preferred)</p>
  
  <p>2) Use the polygon to mask the data that have been read in and extract only the data inside the province of interest, to work with interactively.</p>
  
  <p>My code so far:</p>
  
  <pre><code>import iris
  import geopandas as gpd
  
  #read the shapefile and extract the polygon for a single province
  #(province names stored as variable 'NAME_1')
  Canada=gpd.read_file('CAN_adm1.shp')
  BritishColumbia=Canada[Canada['NAME_1'] == 'British Columbia']
  
  #get the latitude-longitude grid from netcdf file
  cubelist=iris.load('t2m.20090815.nc')
  cube=cubelist[0]
  lats=cube.coord('latitude').points
  lons=cube.coord('longitude').points
  
  #create 2d grid from lats and lons (may not be necessary?)
  [lon2d,lat2d]=np.meshgrid(lons,lats)
  
  #HELP!
  </code></pre>
  
  <p>Thanks very much for any help or advice.</p>
  
  <hr>
  
  <p>UPDATE: Following the great solution from @DPeterK below, my original data can be masked, giving the following:</p>
  
  <p><a href="https://i.stack.imgur.com/FKaDc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FKaDc.png" alt="temperature data from netcdf file masked using shapefile of Canadian provinces"></a></p>