find the last point of line geopanda 1

find the last point of line geopanda

import geopandas as gpd
from shapely.geometry import Point, LineString
line1 = LineString([Point(0,0), Point(-1,-1), Point(2,-3), Point(4,5)])
line2 = LineString([Point(-2,8), Point(7,4), Point(0,-1), Point(0,2)])
gdf = gpd.GeoDataFrame(
    {'City': ['Buenos Aires','Rio de Janeiro'],
     'Country': ['Argentina', 'Brazil'], 'geometry': [line1, line2]})

gdf['first'] = None
gdf['last'] = None

for index, row in gdf.iterrows():
    coords = [(coords) for coords in list(row['geometry'].coords)]
    first_coord, last_coord = [ coords[i] for i in (0, -1) ]
    gdf.at[index,'first'] = Point(first_coord)
    gdf.at[index,'last'] = Point(last_coord)
    gdf

Here is what the above code is Doing:
1. Create a GeoDataFrame with two LineStrings
2. Create two new columns in the GeoDataFrame, ‘first’ and ‘last’
3. Iterate over the rows of the GeoDataFrame
4. For each row, get the coordinates of the LineString
5. Get the first and last coordinates of the LineString
6. Create a Point object from the first and last coordinates
7. Assign the Point object to the ‘first’ and ‘last’ columns

Similar Posts