I have a line shapefile in GeoPandas. How can I extract the start and end coordinates as (x,y) pairs in two separate columns?

import geopandas as gpd
gdf = gpd.read_file(pth_line_shapefile)
gdf['start_coordinates_XY'] = gdf.apply(lambda x: [y[0] for y in x['geometry'].coords], axis=1)

The above code extracts X coordinates of all points in the geometry not the first point (in x,y format)

An example line shapefile linked here


This can make it:

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)

Which results in:


You can tweak that to suit what ever format your need for your points...


Coordinate values are accessed via coords, x, y, and z properties.



Gillies, S. others.(2007). Shapely: Manipulation and analysis of geometric objects. toblerity. org.

  • Perfect! Thanks a lot.
    – PPR
    Apr 17 '20 at 17:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.