如何将矢量点转换为按特定顺序排列的直线

2024-09-28 01:32:23 发布

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

我正在使用一组代表公交线路不同站点的点。我有一个.csv文件,它给出了stop_idlonlatstop_sequence(它决定了公交线路沿线站点的顺序)和direction_id(它是1或0,表示公交线路的方向)。你知道吗

        stop_id                 lat         lon    stop_sequence direction_id   geometry
231519  StopPoint:59:3730058    48.770247   2.348581    5        1  POINT (2.348581 48.770247)
231520  StopPoint:59:3730064    48.759449   2.369324    2        1  POINT (2.369324 48.759449)
231521  StopPoint:59:3730062    48.759647   2.365572    3        1  POINT (2.365572 48.75964699999999)
231522  StopPoint:59:3730068    48.752867   2.377503    0        1  POINT (2.377503 48.75286699999999)
231523  StopPoint:59:3730066    48.756454   2.374298    1        1  POINT (2.374298 48.756454)

我将这个数据帧转换成一个geodataframe,并使用找到的方法here将点转换成线。你知道吗

但它没有考虑gdf的stop_sequence,我得到以下结果:

这不是我想的。我需要将绿点转换成一条考虑stop_sequence顺序的线。 我需要的是一条线,从0站到1站,从1站到2站,从2站到3站,依此类推,直到这条线的最后一站,一个方向,然后另一个方向。你知道吗

python有这样做的方法吗?我也可以使用qgis,但是python会更好。你知道吗


编辑:这里是我使用的代码的简化版本。你知道吗

我在上面展示了一个只与一条总线相关的示例,我使用了更多的总线,并且每条总线都链接到一个route_id。你知道吗

完整的gdf如下所示:

# Since I have to consider many bus line I thought it would be easier to first work with one of them: line_a.
test = gdf.loc[(gdf['route_id'] == 'line_a') & (gdf['direction_id'] == 1)].sort_values('stop_sequence')
test.head()

         stop_id         lat    lon route_id    stop_sequence   direction_id    geometry
494867  StopPoint:59:3730102    48.806131   2.472466    line_a  0   1   POINT (2.472466 48.806131)
246032  StopPoint:59:3730102    48.806131   2.472466    line_a  0   1   POINT (2.472466 48.806131)
233510  StopPoint:59:3730102    48.806131   2.472466    line_a  0   1   POINT (2.472466 48.806131)
246062  StopPoint:59:3730102    48.806131   2.472466    line_a  0   1   POINT (2.472466 48.806131)
246092  StopPoint:59:3730102    48.806131   2.472466    line_a  0   1   POINT (2.472466 48.806131)

然后我使用下面的代码行将lon/lat点转换成字符串:

gdf2 = test.groupby(['route_id'])['geometry'].apply(lambda x: LineString(x.tolist()))
gdf2 = gpd.GeoDataFrame(gdf2, geometry='geometry')

gdf2['route_id'] = gdf2.index #I added this line because route_id was the gdf index and I couldn't .loc[] with it.

             geometry                                         route_id
route_id        
line_a  LINESTRING (2.472466 48.806131, 2.472466 48.80...   line_a

最后我把一切都计划好了:

gdf2.plot(ax=ax, color='mediumaquamarine', alpha=0.7, zorder=0) # Plot of the LineString.
gdf.loc[gdf['direction_id'] == 1].plot(ax=ax, color='green', alpha=0.7, zorder=1) # Plot of the station stops.

Tags: idlineaxroutepointstoplonsequence

热门问题