我目前正在使用 sjoin 從 json 檔案中過濾整個多邊形串列中的點。問題是,如果有重疊的多邊形,我希望它顯示點以及它所在的多邊形。這些點都是勻稱的幾何形狀。
例如:
A點:多邊形1,多邊形2
現在它正在做:
A點:多邊形1
A點:多邊形2
我希望它也只顯示重疊區域中的點,如果可能的話,忽略任何只在一個中的點。
我現在擁有的示例代碼:
filter = gpd.sjoin(pointdataframe, polygons, op='within')
點資料框和多邊形都是地理資料框。多邊形包含所有多邊形,無論它們是重疊的還是單獨的。
我嘗試使用 groupby() 函式,但是它回傳了所有點的完整串列,并且沒有按照我上面想要的方式格式化每個點中包含的多邊形。
uj5u.com熱心網友回復:
- 使用了兩個重疊的示例多邊形
- 生成在此幾何圖形的總邊界上呈線性間隔的點
sjoin()正如你所做的那樣找到與多邊形關聯的點- 現在
groupby()是點索引。這現在允許獲取與點關聯的多邊形串列
樣本輸出
| 指數 | 幾何學 | 聚 |
|---|---|---|
| 55 | 點(52.77777777777778 53.22222222222222) | 0 |
| 56 | 點(54.333333333333336 53.22222222222222) | 0 |
| 57 | 點(55.888888888888886 53.22222222222222) | 0 |
| 58 | 點(57.44444444444444 53.22222222222222) | 0 |
| 61 | 點(46.55555555555556 54.666666666666664) | 1 |
| 62 | 點(48.111111111111114 54.666666666666664) | 1 |
| 63 | 點(49.666666666666664 54.666666666666664) | 1 |
| 64 | 點(51.22222222222222 54.666666666666664) | 1 |
| 65 | 點(52.77777777777778 54.666666666666664) | 0,1 |
| 66 | 點(54.333333333333336 54.666666666666664) | 0,1 |
可視化

完整代碼
import pandas as pd
import numpy as np
import geopandas as gpd
import io
import shapely
gdf_poly = gpd.GeoDataFrame(
geometry=pd.read_csv(
io.StringIO(
"""POLYGON ((59 46, 59 59, 52 59, 52 46, 59 46))
POLYGON ((59 54, 59 59, 45 59, 45 54, 59 54))"""
),
header=None,
sep="\t",
)[0].apply(shapely.wkt.loads),
crs="epsg:4386",
)
# generate some points
gdf_point = gpd.GeoDataFrame(
geometry=[
shapely.geometry.Point(lat, lon)
for lon in np.linspace(*gdf_poly.total_bounds[[1, 3]], 10)
for lat in np.linspace(*gdf_poly.total_bounds[[0, 2]], 10)
],
crs="epsg:4386",
)
# group by points index to get common ones and associated polygon(s)
gdf_points_poly = gpd.sjoin(gdf_point, gdf_poly, op="within").reset_index().groupby("index").agg(
geometry=("geometry", "first"), poly=("index_right", lambda i: ",".join(i.astype(str).tolist()))
).set_crs("epsg:4386")
# visualise ...
m = gdf_poly.explore(height=300, width=500, color="green")
gdf_points_poly.explore(m=m, column="poly", cmap=["blue","red","blue"])
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/446243.html
上一篇:jsonAPI資料到熊貓資料框
