【问题标题】:Extract values from xarray dataset using geopandas multilinestring使用 geopandas multilinestring 从 xarray 数据集中提取值
【发布时间】:2021-05-14 22:15:59
【问题描述】:

我有几百个geopandas 多线串沿着感兴趣的对象追踪(在几年内每周一条线追踪墨西哥湾流),我想使用这些线从其他几个xarray 中提取值数据集,以了解每周沿此路径的海面温度、叶绿素-a 和其他变量。

我不确定如何准确地使用这些geopandas 行从xarray 数据集中提取值。我曾考虑将它们分成点并在每个点获取数据集值,但这似乎有点麻烦。有没有直接的方法来做这个操作?

【问题讨论】:

    标签: python geopandas python-xarray


    【解决方案1】:

    将线分成点然后提取点实际上非常简单!

    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
    

    主要是决定你要采样的点,或者多少点等。

    请注意,地理数据框中的几何对象也有一个插值方法,如果您想在轨迹上的特定点绘制值:

    https://shapely.readthedocs.io/en/stable/manual.html#object.interpolate

    在这种情况下,.apply 可以派上用场:

    gdf.geometry.apply(lambda geom: geom.interpolate(3.0))
    
    0      POINT (2.12132 2.12132)
    1    POINT (12.12132 12.12132)
    Name: geometry, dtype: geometry
    

    【讨论】:

      【解决方案2】:

      由于 GeoPandas 使用与 Pandas 相同的约定,因此最好的方法是在处理时统一数据类型。你可以在 xarray 中这样做:

      xr.Dataset.from_dataframe(df)
      

      【讨论】:

        猜你喜欢
        • 2020-07-12
        • 2021-12-26
        • 1970-01-01
        • 1970-01-01
        • 2018-10-11
        • 2013-10-05
        • 2020-07-09
        • 1970-01-01
        • 2017-09-25
        相关资源
        最近更新 更多