【发布时间】:2021-12-26 23:18:24
【问题描述】:
我正在尝试使用来自 https://psl.noaa.gov/data/gridded/data.pdsi.html 的 pdsi 月平均校准数据从 NetCDF3 数据中提取国家/地区。我正在使用以下代码执行坐标的空间合并并根据世界的 shapefile 识别国家/地区。
# Import shapefile from geopandas
path_to_data = geopandas.datasets.get_path("naturalearth_lowres")
world_shp = geopandas.read_file(path_to_data)
world_shp.head()
# Import netCDF file
ncs = "pdsi.mon.mean.selfcalibrated.nc"
# Read in netCDF as a pandas dataframe
# Xarray provides a simple method of opening netCDF files, and converting them to pandas dataframes
ds = xr.open_dataset(ncs)
pdsi = ds.to_dataframe()
# the index in the df is a Pandas.MultiIndex. To reset it, use df.reset_index()
pdsi = pdsi.reset_index()
# quick check for shpfile plotting
world_shp.plot(figsize=(12, 8));
# use geopandas points_from_xy() to transform Longitude and Latitude into a list of shapely.Point objects and set it as a geometry while creating the GeoDataFrame
pdsi_gdf = geopandas.GeoDataFrame(pdsi, geometry=geopandas.points_from_xy(pdsi.lon, pdsi.lat))
print(pdsi_gdf.head())
# check CRS coordinates
world_shp.crs #shapefile
pdsi_gdf.crs #geodataframe netcdf
# set coordinates equal to each other
# PointsGeodataframe.crs = PolygonsGeodataframe.crs
pdsi_gdf.crs = world_shp.crs
# check coordinates after setting coordinates equal to each other
pdsi_gdf.crs #geodataframe netcdf
#spatial join
join_inner_df = geopandas.sjoin(pdsi_gdf, world_shp, how="inner")
join_inner_df
我遇到的问题是 NetCDF 格式的原始数据由空间覆盖/网格数据组成,其中关键变量 (pdsi) 的值表示每个阴影正方形内的区域(见下图)。到目前为止,只有正方形中间的坐标点是匹配的,我希望每个阴影正方形都匹配它所在的每个国家。例如,如果阴影方块的面积在德国和荷兰的边界内,那么关键变量应该归属于这两个国家。对此问题的任何帮助将不胜感激。
【问题讨论】:
-
还可以查看 regionmask 包 - 它的创建是为了帮助解决此类问题
-
谢谢@MichaelDelgado,我会去看看!
标签: python reverse spatial netcdf geopandas