首页 > 解决方案 > 如何从与配置文件对应的数据框中提取数据?

问题描述

我有一个数据框,它是一个带有坐标和多个其他条目的空间数据。

df.columns=['longitude','latitude',....,'data']

如果我有线条轮廓的坐标,

profile=[(x1,y1),(x2,y2)]

并考虑配置文件具有自定义宽度(5 公里),如何提取数据帧中属于该配置文件的数据行子集?

(在 geopandas 或 shapely 中是否有特定的功能?)

标签: pythonpandasdataframegeopandasshapely

解决方案


  • 使用多个英国城市进行示范
  • 随机选择 4 个城市从这些坐标中dfp.sample(4)生成一个匀称的线串
  • 向这条线添加一个 10 公里的缓冲区(这意味着它变成了一个多边形)。注意使用 CRS 系统能够以公里为单位定义距离
  • 对所有城市进行缓冲线的空间连接
  • 图表显示已确定其他城市(不只是在线上的 4 个城市)
import pandas as pd
import numpy as np
import geopandas as gpd
import shapely.geometry
import requests, json
import plotly.express as px

# source some points and polygons
# fmt: off
dfp = pd.read_html("https://www.latlong.net/category/cities-235-15.html")[0]
dfp = gpd.GeoDataFrame(
    dfp,
    geometry=dfp.loc[:,["Longitude","Latitude"]].apply(shapely.geometry.Point, axis=1),
    crs="EPSG:4326",
)
# fmt: on

# construct a LineString from 4 random points
line = shapely.geometry.LineString(
    dfp.sample(4).loc[:, ["Longitude", "Latitude"]].values
)
# add a buffer to LineString (hence becomes a polygon)
DISTANCE = 10 ** 4  # 10km
line = (
    gpd.GeoSeries([line], crs="EPSG:4326")
    .to_crs(dfp.estimate_utm_crs())
    .buffer(DISTANCE)
    .to_crs("EPSG:4326")
)
df_near = gpd.GeoDataFrame(geometry=line).sjoin(dfp)

px.scatter_mapbox(df_near, lat="Latitude", lon="Longitude").update_layout(
    mapbox={
        "style": "carto-positron",
        "zoom": 4,
        "layers": [
            {
                "source": json.loads(line.to_json()),
                "below": "traces",
                "type": "fill",
                "color": "lightgrey",
            }
        ],
    }
)

在此处输入图像描述

#Edit 删除了给出错误消息的不需要的空间


推荐阅读