2

I'm new in Geopandas and I try to creat my first script. I succeeded to open a shapefile and maked a union of all entity and an envelope. As it said in Geopandas doc, after these 2 geometric manipulations it returns Geoserie. But how can I convert my Geoserie to a Geodataframe to finally export it to a shapefile ?

I try this on point shapefile but my Geodataframe is empty...

import sys
import geopandas as gpd

shp = (sys.argv[1])

gdf = gpd.read_file(shp)

union = gdf.unary_union

env = union.envelope

envgdf = gpd.GeoDataFrame()

envgdf['geometry'] = env
envgdf.geometry.name

print("\nGeoDataFrame :\n", envgdf)

Returns :

GeoDataFrame :
Empty GeoDataFrame
Columns: [geometry]
Index: []
8

The type of env here is a Shapely Polygon. In this line

envgdf['geometry'] = env

You're trying to assign a Polygon to a Geometry column. You can instead create a Geoseries from the Polygon and create a Geodataframe based on that. Here's the updated code:

import sys
import geopandas as gpd

shp = (sys.argv[1])

gdf = gpd.read_file(shp)

union = gdf.unary_union

env = union.envelope

# Replace these three lines:

#envgdf = gpd.GeoDataFrame()
#envgdf['geometry'] = env
#envgdf.geometry.name

# With
envgdf = gpd.GeoDataFrame(gpd.GeoSeries(env))

# Edit: Following Tim C's comment below, this line sets geometry for resulting geodataframe
envgdf = envgdf.rename(columns={0:'geometry'}).set_geometry('geometry')

print("\nGeoDataFrame :\n", envgdf)
  • It's ok ! envgdf is a geodataframe but without a true geometry column. When I try to export as a shapefile, python returns AttributeError: No geometry data set yet (expected in column 'geometry'.Column with geometry is names 0... – Tim C. Dec 21 '17 at 12:32
  • 3
    Ok I found myself. envgdf = envgdf.rename(columns={0:'geometry'}).set_geometry('geometry') solves this issue. – Tim C. Dec 21 '17 at 12:50
  • @TimC. you should consider writing an answer from your comment above – gcamargo Jun 28 '18 at 15:12
0

GeoDataframe now accepts a geometry keyword argument. Taking advantage of that, we can write

envgdf = gpd.GeoDataFrame(geometry=gpd.GeoSeries(env))

This automatically sets the GeoSeries as the geometry column.

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.