我有一个从shapefile创建的geopandas数据框。
我想根据以下列对数据帧进行排序:“名称”和行块也应按地理位置排序,以便将具有相同名称的所有附近块组合在一起。
我该怎么做这种排序?
我尝试过:1。我计算每个线串的平均坐标:
df['mean_coord'] = df.geometry.apply(lambda g: [np.mean(g.xy[0]),np.mean(g.xy[1])])
但我不确定,如果这是最好/最优雅甚至是正确的方法。除此之外,我不知道如何从分组元素回到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)