[GIS] Buffering line with flat cap style using GeoPandas

buffergeopandaspythonshapefileshapely

I'm interested in buffering a linestring geometry using a flat cap style rather than the default round cap style using GeoPandas. I see shapely, which geopandas is based off, has the option to do that:

object.buffer(distance, resolution=16, cap_style=2, join_style=1, mitre_limit=1.0)

However, when I try to integrate the cap style into my geopandas script

import geopandas as gp

shp = r'X:\temp\line_shapefile.shp'
outshp =r'X:\temp\buffered_line_shapefile.shp'

df = gp.GeoDataFrame.from_file(shp)
buffer = df.buffer(100, cap_style=2)

buffer.to_file(outshp)

it throws an error

Traceback (most recent call last):

  File "<ipython-input-12-9660d1a63146>", line 7, in <module>
    buffer = df.buffer(100, cap_style=2)

TypeError: buffer() got an unexpected keyword argument 'cap_style'

What is the correct implimentation of the flat cap style buffer in GeoPandas?

Best Answer

GeoPandas isn't passing through all arguments to the shapely buffer method. Instead you can use the standard pandas apply method to call buffer on each geometry individually, e.g.:

# Assumes that geometry will be the geometry column
capped_lines = df.geometry.apply(lambda g: g.buffer(100, cap_style=2))

Also, not that this returns a GeoPandas GeoSeries object, so if you need the attributes (and projection for that matter, though that may be an outstanding issue) you'll need to overwite the geometry column in the original GeoDataFrame.