0

I have two point shapefiles (with just one point each, let's call them 'Origin' and 'Destination'). I need to find the shortest path between them over a street network extracted using OSMnx from OpenStreetMap. For this, the points' coordinates are needed. First, I have each file read using GeoPandas as follows:

import geopandas as gpd
origin_fp = "C:/Users/User Name/Python_experiment/Origin.shp"
destination_fp = "C:/Users/User Name/Python_experiment/Destination.shp"
origin = gpd.read_file(origin_fp)
destination = gpd.read_file(destination_fp)

Once this is done, what is the syntax for extracting the coordinates of each feature in the shapefile?

They already have the same coordinate system to which I will project my graph.

Must the shapefiles have attributes for latitude and longitude?

1 Answer 1

4

It depends on the format of the coordinates you want

import geopandas as gpd
df = gpd.read_file("points.shp")
df.head(3)
   FID      geometry
0   0   POINT (-0.18411 0.47266)
1   1   POINT (0.16016 0.34106)
2   2   POINT (-0.46957 0.39932)
df['lon']  = df.geometry.x
df['lat']  = df.geometry.y
df['coords'] = df.geometry.apply(lambda p: list(p.coords)[0])
df.head(3)
   FID  geometry                       lon         lat              coords
0   0   POINT (-0.18411 0.47266)    -0.184108   0.472664    (-0.18410841450105575, 0.47266361459480355)
1   1   POINT (0.16016 0.34106)      0.160162   0.341056    (0.16016249583069841, 0.34105550781849137)
2   2   POINT (-0.46957 0.39932)    -0.469574   0.399324    (-0.4695739603914672, 0.39932386352712257)
2
  • So far, df.geometry.x and df.geometry.y seems to work for retrieving the coordinates. When I have resolved other issues that have arisen with my script, I'll know for sure. Commented Jul 16, 2021 at 17:42
  • The geometry is a shapely geomettry therefore df.geometry.x and df.geometry.y is correct.
    – gene
    Commented Jul 16, 2021 at 19:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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