Geopandas – Solving Buffering Issues that Delete Attribute Data

buffergeopandaspolygonpythonshapefile

I am trying to use Python and GeoPandas to create variable distance buffers for a polygons shapefile I have. I brought this shapefile into python using GeoPandas. One of the columns of the GeoDataFrame has a Distances column with a unique distance for each polygon (row). I want to buffer all of the polygons in the shapefile/GeoDataFrame, but where each individual polygon is buffered at a distance corresponding to its own corresponding distance in the Distances column.

I tried this:

polygons = gpd.read_file('polygons.shp')
distances = polygons['Distances']
polygons_buffered = polygons.buffer(distances)
polygons_buffered.to_file("polygons_buffered.shp")
polygons_buffered = gpd.read_file('polygons_buffered.shp')
polygons_buffered.head()

And then I see that the only data that is preserved in the attribute table is and FID and geometry, but all of my attribute columns with all of my associated data are gone. I brought the shapefile into QGIS, and see that the variable distances buffers were created as a wanted, but that these buffers were missing all of the data I wanted them to contain.

How can I fix my code so that I create these variable distance buffers based on my "Distances" column, but so that all of the attribute data within each of the original polygons is preserved within its newly buffered polygon?

Best Answer

Looks like you're only storing the geometry field in the polygons_buffered GDF. You can apply the buffer function directly to the original GDF and either modify the geometry field in place or store in another gdf (which requires you to store more than just the computed field in the new gdf, which is where you had issues with your original code). Since you're exporting immediately as a SHP, I'd go with the former option:

polygons['geometry'] = polygons['geometry'].buffer(polygons['Distance'])
polygons.head()
polygons.plot()