Skip to content

Instantly share code, notes, and snippets.

@rmania
Created March 13, 2017 21:06
Show Gist options
  • Save rmania/8c88377a5c902dfbc134795a7af538d8 to your computer and use it in GitHub Desktop.
Save rmania/8c88377a5c902dfbc134795a7af538d8 to your computer and use it in GitHub Desktop.
flatten geometry series (3D to 2D) in geopandas dataframe
# Often when reading in a ShapeFile from Basemap, you'll get: "ValueError: readshapefile can only handle 2D shape types"
# A trick can be to convert your geometry in your GeoPandas Dataframe and restoring the new flattened 2D geometry
# series back into a shapefile and try again.
# edit from http://stackoverflow.com/questions/33417764/basemap-readshapefile-valueerror
from shapely.geometry import Polygon, MultiPolygon, shape, Point
import geopandas as gp
def convert_3D_2D(geometry):
'''
Takes a GeoSeries of 3D Multi/Polygons (has_z) and returns a list of 2D Multi/Polygons
'''
new_geo = []
for p in geometry:
if p.has_z:
if p.geom_type == 'Polygon':
lines = [xy[:2] for xy in list(p.exterior.coords)]
new_p = Polygon(lines)
new_geo.append(new_p)
elif p.geom_type == 'MultiPolygon':
new_multi_p = []
for ap in p:
lines = [xy[:2] for xy in list(ap.exterior.coords)]
new_p = Polygon(lines)
new_multi_p.append(new_p)
new_geo.append(MultiPolygon(new_multi_p))
return new_geo
geodf_2d = gp.GeoDataFrame.from_file(shp_file) # plug_in your shapefile
geodf_2d.geometry = convert_3D_2D(geodf_2d.geometry) # new geodf with 2D geometry series
# geodf_2d.to_file(path + shapefile.shp, driver = 'ESRI Shapefile') will sore a shapefile with 2D shape types
@gilcapote
Copy link

Thanks! works great.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment