掩码地图边界之外的数据

首先需要下载地图数据(https://www.naturalearthdata.com/),获取地图边界,然后将其进行光栅化(rasterize),提取光栅化以后的数据,利用np.ma.array的掩码功能进行掩码。

from rasterio import features
import numpy as np
import xarray as xr
from affine import Affine
import geopandas
def transform_from_latlon(lat,lon):
    lat=np.asarray(lat)
    lon=np.asarray(lon)
    trans=Affine.translation(lon[0],lat[0])
    scale=Affine.scale(lon[1]-lon[0],lat[1]-lat[0])
    return trans*scale

def rasterize(shapes,coords,fill=np.nan,**kwargs):
    transform=transform_from_latlon(coords['latitude'],coords['longitude'])
    out_shape=(len(coords['latitude']),len(coords['longitude']))
    raster=features.rasterize(shapes,out_shape=out_shape,fill=fill,transform=transform,dtype=float,**kwargs)
    return xr.DataArray(raster,coords=coords,dims=('latitude','longitude'))

def maskarray():
    states=geopandas.read_file('D:\\research\\data\\shapefile\\ne_10m_admin_0_countries')
    china0= states.query("SOVEREIGNT =='China'").reset_index(drop=True)
    China_ids = {k: i for i, k in enumerate(china0.NAME_PT)}
    shapes = [(shape, n) for n, shape in enumerate(china0.geometry)]
    ds = xr.Dataset(coords={'longitude': np.linspace(99, 129, num=301),'latitude': np.linspace(27, 54, num=271)})
    ds['country'] = rasterize(shapes, ds.coords)
    return ds.country.values
参考https://gist.github.com/shoyer/0eb96fa8ab683ef078eb

你可能感兴趣的:(掩码地图边界之外的数据)