计算点的整个 GeoDataFrame 的质心

Calculate centroid of entire GeoDataFrame of points

我想从 geojson 文件中导入一些 waypoints/markers。然后确定所有点的质心。我的代码计算每个点的质心,而不是系列中所有点的质心。如何计算系列中所有点的质心?

import geopandas

filepath = r'Shiloh.json'

gdf = geopandas.read_file(filepath)

xyz = gdf['geometry'].to_crs('epsg:3587')

print(type(xyz))
print(xyz)

# xyz is a geometry containing POINT Z

c = xyz.centroid


# instead of calculating the centroid of the collection of points
# centroid has calculated the centroid of each point. 
# i.e. basically the same X and Y data as the POINT Z.

print(type(xyz)) 和 print(xyz) 的输出

<class 'geopandas.geoseries.GeoSeries'>
0    POINT Z (2756810.617 248051.052 0.000)
1    POINT Z (2757659.756 247778.482 0.000)
2    POINT Z (2756907.786 248422.534 0.000)
3    POINT Z (2756265.710 248808.235 0.000)
4    POINT Z (2757719.694 248230.174 0.000)
5    POINT Z (2756260.291 249014.991 0.000)
6    POINT Z (2756274.410 249064.239 0.000)
7    POINT Z (2757586.742 248437.232 0.000)
8    POINT Z (2756404.511 249247.296 0.000)
Name: geometry, dtype: geometry

变量'c'报告为(每个点的质心,而不是 9 POINT Z 元素的质心):

0    POINT (2756810.617 248051.052)
1    POINT (2757659.756 247778.482)
2    POINT (2756907.786 248422.534)
3    POINT (2756265.710 248808.235)
4    POINT (2757719.694 248230.174)
5    POINT (2756260.291 249014.991)
6    POINT (2756274.410 249064.239)
7    POINT (2757586.742 248437.232)
8    POINT (2756404.511 249247.296)
dtype: geometry

首先dissolve the GeoDataFrame to get a single shapely.geometry.MultiPoint对象,然后找到质心:

In [8]: xyz.dissolve().centroid
Out[8]:
0    POINT (2756876.613 248561.582)
dtype: geometry

来自geopandas docs

dissolve() can be thought of as doing three things:

  • it dissolves all the geometries within a given group together into a single geometric feature (using the unary_union method), and
  • it aggregates all the rows of data in a group using groupby.aggregate, and
  • it combines those two results.

请注意,如果您有包含重复几何图形的行,则使用此方法计算的质心不会对重复项进行适当加权,因为溶解会在计算质心之前首先删除重复记录:


In [9]: gdf = gpd.GeoDataFrame({}, geometry=[
   ...:     shapely.geometry.Point(0, 0),
   ...:     shapely.geometry.Point(1, 1),
   ...:     shapely.geometry.Point(1, 1),
   ...:     ])

In [10]: gdf.dissolve().centroid
Out[10]:
0    POINT (0.50000 0.50000)
dtype: geometry

要准确计算包含重复点的集合的质心,请直接创建一个 shapely.geometry.MultiPoint 集合:

In [11]: mp = shapely.geometry.MultiPoint(gdf.geometry)

In [12]: mp.centroid.xy
Out[12]: (array('d', [0.6666666666666666]), array('d', [0.6666666666666666]))