簡體   English   中英

計算多邊形中的點並將結果寫入(地理)數據幀

[英]Count Points in Polygon and write result to (Geo)Dataframe

我想計算每個多邊形有多少點

# Credits of this code go to: https://stackoverflow.com/questions/69642668/the-indices-of-the-two-geoseries-are-different-understanding-indices/69644010#69644010
import pandas as pd
import numpy as np
import geopandas as gpd
import shapely.geometry
import requests

# 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))
res = requests.get("https://opendata.arcgis.com/datasets/69dc11c7386943b4ad8893c45648b1e1_0.geojson")
df_poly = gpd.GeoDataFrame.from_features(res.json())
# fmt: on

現在我sjoin兩個。 我首先使用df_poly ,以便將點dfp添加到GeoDataframe df_poly

df_poly.sjoin(dfp)

現在我想計算每個polygon有多少points 我想

df_poly.sjoin(dfp).groupby('OBJECTID').count()

但這不會向GeoDataframe df_poly添加一column ,其中GeoDataframe每個groupcount

您需要使用合並將count()的輸出中的一列添加回原始 DataFrame。 我使用了幾何列並將其重命名為n_points

df_poly.merge(
    df_poly.sjoin(
        dfp
    ).groupby(
        'OBJECTID'
    ).count().geometry.rename(
        'n_points'
    ).reset_index())

這是這個問題后續兩個 GeoSeries 的索引不同 - 理解索引

  • 空間連接的right_index給出多邊形的索引,因為多邊形位於空間連接的右側
  • 因此系列gpd.sjoin(dfp, df_poly).groupby("index_right").size().rename("points")然后可以簡單地加入多邊形GeoDataFrame以給出找到的點數
  • 注意how="left"以確保它是左連接,而不是內部連接。 在這種情況下,任何沒有點的多邊形都有NaN您可能想要fillna(0)
import pandas as pd
import numpy as np
import geopandas as gpd
import shapely.geometry
import requests

# source some points and polygons
# fmt: off
dfp = pd.read_html("https://www.latlong.net/category/cities-235-15.html")[0]
dfp = pd.concat([dfp,dfp]).reset_index(drop=True)
dfp = gpd.GeoDataFrame(dfp, geometry=dfp.loc[:,["Longitude", "Latitude",]].apply(shapely.geometry.Point, axis=1))
res = requests.get("https://opendata.arcgis.com/datasets/69dc11c7386943b4ad8893c45648b1e1_0.geojson")
df_poly = gpd.GeoDataFrame.from_features(res.json())
# fmt: on

df_poly.join(
    gpd.sjoin(dfp, df_poly).groupby("index_right").size().rename("points"),
    how="left",
)

基於 Fergus McClean 提供的答案,這甚至可以用更少的代碼完成:

df_poly.merge(df_poly.sjoin(dfp).groupby('OBJECTID').size().rename('n_points').reset_index())

然而,Rob Raymond 提出的方法 ( .join() ) 將兩個dataframes結合起來,保留了沒有計數的條目。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM