import geopandas as gpd
import numpy as np
import shapely.geometry as sg
import xarray as xr
# Setup an example DataArray:
y = np.arange(20.0)
x = np.arange(20.0)
da = xr.DataArray(
data=np.random.rand(y.size, x.size),
coords={"y": y, "x": x},
dims=["y", "x"],
)
# Setup an example geodataframe:
gdf = gpd.GeoDataFrame(
geometry=[
sg.LineString([(0.0, 0.0), (5.0, 5.0)]),
sg.LineString([(10.0, 10.0), (15.0, 15.0)]),
]
)
# Get the centroids, and create the indexers for the DataArray:
centroids = gdf.centroid
x_indexer = xr.DataArray(centroids.x, dims=["point"])
y_indexer = xr.DataArray(centroids.y, dims=["point"])
# Grab the results:
da.sel(x=x_indexer, y=y_indexer, method="nearest")
<xarray.DataArray (point: 2)>
array([0.80121949, 0.34728138])
Coordinates:
y (point) float64 3.0 13.0
x (point) float64 3.0 13.0
* point (point) int64 0 1
由于GeoPandas使用与Pandas相同的约定,因此最好的方法是在处理时统一数据类型。您可以在xarray中通过以下方式执行此操作:
事实上,将线分解为点,然后提取点非常简单
主要的事情是决定你想在哪一点取样,或者取样多少点,等等
请注意,geodataframe中的几何体对象也有插值方法,如果您希望沿轨迹在特定点绘制值:
https://shapely.readthedocs.io/en/stable/manual.html#object.interpolate
在这种情况下,
.apply
可以派上用场:相关问题 更多 >
编程相关推荐