计算整个 GeoDataFrame 点的质心

2024-03-21

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

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

first dissolve https://geopandas.org/en/stable/docs/reference/api/geopandas.GeoDataFrame.dissolve.html#geopandas.GeoDataFrame.dissolveGeoDataFrame 获取单个shapely.geometry.MultiPoint https://shapely.readthedocs.io/en/stable/manual.html#MultiPoint对象,然后找到质心:

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

来自geopandas 文档 https://geopandas.org/en/stable/docs/user_guide/aggregation_with_dissolve.html:

solve() 可以被认为做了三件事:

  • 它将给定组中的所有几何图形分解为单个几何特征(使用 unary_union 方法),并且
  • 它使用 groupby.aggregate 将所有数据行聚合到一个组中,并且
  • 它结合了这两个结果。

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


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]))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

计算整个 GeoDataFrame 点的质心 的相关文章

随机推荐