6

I have a GeoPandas GeoDataFrame that looks like this:

shape_id    geometry
1000252     LINESTRING (4.91790 52.34725, 4.91797 52.34715...
1000254     LINESTRING (4.80382 52.34495, 4.80413 52.34500...
1000255     LINESTRING (4.89922 52.37811, 4.89923 52.37807...

I would like to extract the coordinates in the geometry column for each shape_id row individually as a list. For example, the output for shape_id = 1000252 should be as follows:

[[52.34725, 4.91790],
 [52.34715, 4.91797],
 [52.34742, 4.91723],
 [52.34752, 4.91713]]

What is the most efficient way to achieve this?

0

3 Answers 3

5

Maybe not "most efficient" but it will get you the result you want:

import geopandas as gpd

df = gpd.read_file(r'/home/bera/Drives/Lagring/GISdata/OpenStreetmap/sweden-latest-free.shp/gis_osm_railways_free_1.shp')

def f(frame):
    xy = frame.geometry.xy
    longs = xy[0].tolist()
    lats = xy[1].tolist()
    return [list(z) for z in zip(lats, longs)]

df['coords'] = df.apply(f, axis=1)

1 second for 25000 features

5

You can use this one-liner if you are happy with a list of tuples instead of a list of lists:

df['coords'] = df.geometry.apply(lambda geom: list(geom.coords))

enter image description here

1

Another option is to use the .mapping() method.

import geopandas as gpd
from shapely.geometry import LineString, mapping

d = {
    'id': [1, 2],
    'geometry': [
         LineString([
             (350630.319649, 5333438.389906),
             (410389.192817, 5298093.202727),
             (466139.848883, 5303194.569949),
             (500391.885943, 5310482.237409),
             (522254.888322, 5300643.886338),
             (547761.72443, 5287890.468284),
             (594038.412798, 5288254.851657),
             (620638.399026, 5307931.553798),
             (643230.16815, 5355301.392285)
             ]),
         LineString([
             (465059.389802, 5337643.246403),
             (428840.7437, 5395427.193238)]
             )]
    }

gdf = gpd.GeoDataFrame(d, crs="EPSG:25832")

def line_to_coords(geom):
    m = mapping(geom)
    list_of_tuples = m['coordinates'] # alternative -> geom.coords[:]
    list_of_lists = list(map(list, list_of_tuples))
    return list_of_lists

gdf['coords'] = gdf.apply(lambda row: line_to_coords(row.geometry), axis=1)

print(gdf)

The above code will result in:

   id  ...                                             coords
0   1  ...  [[350630.319649, 5333438.389906], [410389.1928...
1   2  ...  [[465059.389802, 5337643.246403], [428840.7437...

[2 rows x 3 columns]

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.