按线路名称和地理位置对 GeoPandas 进行排序

Sort GeoPandas by Name Of Line And By Geographic Location

我有一个从 shapefile 创建的 geopandas 数据框。

我想根据以下列对我的数据框进行排序:"name" 并且行块也应按地理位置排序,这样所有具有相同名称的附近块都被组合在一起。

如何进行这种排序?

我尝试过的: 1. 我计算每个线串的平均坐标:

df['mean_coord'] = df.geometry.apply(lambda g: [np.mean(g.xy[0]),np.mean(g.xy[1])])
  1. 我根据 "name" 列对数据帧进行分组,然后根据平均坐标对结果数据帧进行排序:

    grouped=df.sort_values(['mean_coord'],ascending=False).groupby('name')

但我不确定,这是否是 best/most 优雅甚至正确的方法。除此之外,我不知道如何从分组元素返回到 pandas 数据框?

首先,我将向您展示我硬编码并假定为代表性数据集的内容。这确实是您应该在问题中提供的内容,但这个假期我感觉很慷慨:

from shapely.geometry import Point, LineString
import geopandas

line1 = LineString([
    Point(0, 0),
    Point(0, 1),
    Point(1, 1),
    Point(1, 2),
    Point(3, 3),
    Point(5, 6),
])

line2 = LineString([
    Point(5, 3),
    Point(5, 5),
    Point(9, 5),
    Point(10, 7),
    Point(11, 8),
    Point(12, 12),
])

line3 = LineString([
    Point(9, 10),
    Point(10, 14),
    Point(11, 12),
    Point(12, 15),
])

gdf = geopandas.GeoDataFrame(
    data={'name': ['A', 'B', 'A']},
    geometry=[line1, line2, line3]
)

所以现在我要计算每条线的质心的 x 和 y 坐标,对它们取平均值,按线的平均值和名称排序,删除中间列。

output = (
    gdf.assign(x=lambda df: df['geometry'].centroid.x)
       .assign(y=lambda df: df['geometry'].centroid.y)
       .assign(rep_val=lambda df: df[['x', 'y']].mean(axis=1)) 
       .sort_values(by=['name', 'rep_val']) 
       .loc[:, gdf.columns] 
)

print(output)

  name                                       geometry
0    A      LINESTRING (0 0, 0 1, 1 1, 1 2, 3 3, 5 6)
2    A         LINESTRING (9 10, 10 14, 11 12, 12 15)
1    B  LINESTRING (5 3, 5 5, 9 5, 10 7, 11 8, 12 12)