【发布时间】:2021-12-31 05:24:57
【问题描述】:
您好,我在底部使用以下代码从坐标中提取国家/地区。请参阅以下网址,该网址提供了更详细的代码说明:Extracting countries from NetCDF data using geopandas。
我的主要变量/值是来自https://psl.noaa.gov/data/gridded/data.pdsi.html 的月平均 pdsi 值。下图表示由下面的代码创建的可视化的一部分。阴影方块表示 pdsi 值的空间区域,与世界的 shapefile 重叠。
从比利时的图片可以看出,与比利时国土面积相接的4个方格也与其他国家相接。如果我将基值归因于比利时,我相信这会高估平均 pdsi 值。尤其是考虑到底部的两个方块几乎不接触比利时时,这些值在计算平均值时的权重应该显着降低。因此,有没有一种方法可以结合某种加权平均值,其中一个国家内每个正方形的面积可以用作调整每个 pdsi 值的权重?此外,我希望不仅为比利时,而且为所有国家/地区都标准化此流程。
任何帮助将不胜感激!
import geopandas as gpd
import numpy as np
import plotly.express as px
import requests
from pathlib import Path
from zipfile import ZipFile
import urllib
import shapely.geometry
import xarray as xr
# download NetCDF data...
# fmt: off
url = "https://psl.noaa.gov/repository/entry/get/pdsi.mon.mean.selfcalibrated.nc?entryid=synth%3Ae570c8f9-ec09-4e89-93b4-babd5651e7a9%3AL2RhaV9wZHNpL3Bkc2kubW9uLm1lYW4uc2VsZmNhbGlicmF0ZWQubmM%3D"
f = Path.cwd().joinpath(Path(urllib.parse.urlparse(url).path).name)
# fmt: on
if not f.exists():
r = requests.get(url, stream=True, headers={"User-Agent": "XY"})
with open(f, "wb") as fd:
for chunk in r.iter_content(chunk_size=128):
fd.write(chunk)
ds = xr.open_dataset(f)
pdsi = ds.to_dataframe()
pdsi = pdsi.reset_index().dropna() # don't care about places in oceans...
# use subset for testing... last 5 times...
pdsim = pdsi.loc[pdsi["time"].isin(pdsi.groupby("time").size().index[-5:])]
# create geopandas dataframe
gdf = gpd.GeoDataFrame(
pdsim, geometry=pdsim.loc[:, ["lon", "lat"]].apply(shapely.geometry.Point, axis=1)
)
# make sure that data supports using a buffer...
assert (
gdf["lat"].diff().loc[lambda s: s.ne(0)].mode()
== gdf["lon"].diff().loc[lambda s: s.ne(0)].mode()
).all()
# how big should the square buffer be around the point??
buffer = gdf["lat"].diff().loc[lambda s: s.ne(0)].mode().values[0] / 2
gdf["geometry"] = gdf["geometry"].buffer(buffer, cap_style=3)
# Import shapefile from geopandas
path_to_data = gpd.datasets.get_path("naturalearth_lowres")
world_shp = gpd.read_file(path_to_data)
# the solution... spatial join buffered polygons to countries
# comma separate associated countries
gdf = gdf.join(
world_shp.sjoin(gdf.set_crs("EPSG:4326"))
.groupby("index_right")["name"]
.agg(",".join)
)
gdf["time_a"] = gdf["time"].dt.strftime("%Y-%b-%d")
# simplest way to test is visualise...
px.choropleth_mapbox(
gdf,
geojson=gdf.geometry,
locations=gdf.index,
color="pdsi",
hover_data=["name"],
animation_frame="time_a",
opacity=.3
).update_layout(
mapbox={"style": "carto-positron", "zoom": 1},
margin={"l": 0, "r": 0, "t": 0, "b": 0},
)
【问题讨论】:
-
这听起来像是一个科学问题,而不是一个编码问题。 SO 适用于您陈述您的方法并且您需要帮助编码该方法的问题
标签: python spatial geopandas reverse-geocoding shapely