TransWikia.com

How do I extract points from a LineString or Polygon data frame and make a dictionary of point data frames?

Geographic Information Systems Asked by Michael Wallace on February 5, 2021

I am building some pre-processing routines for 3D visualization of GIS data and I have several line and polygon shapefiles with multiple features. I want to extract the points for each of the features along with the feature attributes and create a dictionary of point geo-dataframes. This I suspect is easy to do, but I am not quite sure how to index into the linestring within a geodataframe.

2 Answers

Creating points using the apply function doesn't require a dict as they remain indexed in the output dataframe. We can use list comprehension with an apply function to solve in one line:

gdf['points'] = gdf.apply(lambda x: [y for y in x['geometry'].coords], axis=1)

and then call:

gdf.to_dict('records')

Answered by Adam Flaum on February 5, 2021

I had the same question, here we can use a lambda function:

import geopandas as gpd

gdf = gpd.read_file('some_lines.shp')

say your geodataframe looks like this:

   id xs_ID Orientatio                                           geometry
0   0     W      SW-NE  LINESTRING (4017476.264886954 19792128.2156728)
1   1     E        N-S  LINESTRING (4030453.382825969 19837548.1284593)

Simply write a function to extract the points from the linestrings:

def linestring_to_points(feature,line):
    return {feature:line.coords}

gdf['points'] = gdf.apply(lambda l: linestring_to_points(l['xs_ID'],l['geometry']),axis=1)

now if you print gdf['points']:

0    {'W': ((4017476.2648869543, 19792128.215672825...
1    {'E': ((4030453.382825969, 19837548.128459394)...

The same routine should work with polygons too! (amusing gdf now has polygons instead of lines):

def poly_to_points(feature,poly):
    return {feature:poly.exterior.coords}

gdf['points'] = gdf.apply(lambda p: linestring_to_points(p['xs_ID],p['geometry']),axis=1)

Answered by rosskush on February 5, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP