对多边形中的点进行计数,并将结果写入(Geo)数据帧

2024-09-29 03:36:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我想计算每个多边形有多少个点

# 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

现在我{}这两个。我首先使用df_poly,以便将点dfp添加到GeoDataframe{}

df_poly.sjoin(dfp)

现在我想计算每个polygon有多少points。 我想

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

但这并没有在{}{}中添加一个{},每个{}的{}


Tags: ofthehttpsimportcomdfasrequests
3条回答

这是这个问题的后续问题The indices of the two GeoSeries are different - Understanding Indices

  • 空间连接的右索引给出了多边形的索引,因为多边形位于空间连接的右侧
  • 因此,序列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",
)

您需要使用merge将count()输出中的一列添加回原始数据帧。我使用了geometry列并将其重命名为n_points

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

在Answer Fergus McClean提供的基础上,甚至可以用更少的代码完成:

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

但是,Rob Raymond提出的将两个dataframes合并的方法(.join())保留了没有计数的条目

相关问题 更多 >