How do I extract points from a LineString or Polygon data frame and make a dictionary of point data frames?
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)
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')