Python GeoPandas – Writing an Empty GeoDataFrame to a Shapefile

exportgeodataframegeopandaspythonshapefile

I don't know why this is so hard to find or to do, but how does one create an empty .shp with geopandas?

I essentially want to duplicate the processes of creating a type: polygon shapefile from QGIS, but in a Python script. There is no data to append at this stage. I understand the error, but I am not sure how to add data without adding data. Do I need to do something with schema?

def create_empty(save_name):
    df = gpd.GeoDataFrame(columns=['id', 'geometry'], geometry='geometry')
    df.set_crs(4326)
    print(df)
    df.to_file(filename=f'./QGIS_inputs/{save_name}.shp', driver='ESRI Shapefile')

The error that I get:

ValueError: Cannot write empty DataFrame to file.

Best Answer

Geopandas derives the schema from the geodataframe if you don't specify it. And since your geodataframe is empty, geopandas can't derive a schema.

If you want to save an empty shapefile, you need to pass a fiona schema dict that defines the geometry type and at least one column (that's a shapefile restriction, not applicable to all output formats):

import geopandas

shp_fname = "test.shp"
schema = {"geometry": "Polygon", "properties": {"id": "int"}}
crs = "EPSG:4326"

df = geopandas.GeoDataFrame(geometry=[])

df.to_file(shp_fname, driver='ESRI Shapefile', schema=schema, crs=crs)

More details on schemas: