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)


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?


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.

| improve this answer | |

GeoPandas now pass kwargs to shapely, so you can do below now:

gdf.geometry.to_crs("epsg:3857").buffer(10, cap_style=2)

PR: https://github.com/geopandas/geopandas/pull/535

Update: reason for change crs to 3857 is control on buffer radius in meter, else geopandas raise below warning:

UserWarning: Geometry is in a geographic CRS. Results from 'buffer' are likely incorrect. Use 'GeoSeries.to_crs()' to re-project geometries to a projected CRS before this operation.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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