python - 如何从与配置文件对应的数据框中提取数据?
问题描述
我有一个数据框,它是一个带有坐标和多个其他条目的空间数据。
df.columns=['longitude','latitude',....,'data']
如果我有线条轮廓的坐标,
profile=[(x1,y1),(x2,y2)]
并考虑配置文件具有自定义宽度(5 公里),如何提取数据帧中属于该配置文件的数据行子集?
(在 geopandas 或 shapely 中是否有特定的功能?)
解决方案
- 使用多个英国城市进行示范
- 随机选择 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 删除了给出错误消息的不需要的空间
推荐阅读
- unit-testing - 如何修复 Laravel 7.x phpunit 中未定义的方法错误?
- sql - 分组依据和聚合函数的问题
- javascript - 即使答案正确,四舍五入到小数点后仍显示错误的功能测试?
- python - 转换数据帧:只有整数标量数组可以转换为标量索引
- javascript - React:如果运行另一个事件函数,变量将重置为默认值
- python - 如何在条形图上绘制一条线
- python - For循环函数只返回相同的值
- html - 使用 HTML/CSS 在新行中显示图像
- kubernetes - GKE 负载均衡器服务上的最大端口数
- excel - 如果在同一工作表中满足条件,如何复制列