2

I have a multipolygon GeoPandas DataFrame. I want to create a KML file from each polygon of geodataframe.

gdf

sites   geometry
0   site1   POLYGON ((-83.45951 35.03725, -83.45963 35.037...
1   site2   POLYGON ((-83.46075 35.03702, -83.46086 35.037...
2   site3   POLYGON ((-76.56159 38.89046, -76.56166 38.890...
3   site4   POLYGON ((-76.55872 38.89012, -76.55875 38.890...
4   site5   POLYGON ((-59.86998 -2.40509, -59.87006 -2.405...

I've done this so far:

fiona.supported_drivers['KML'] = 'rw' #fiona library wrapped by geopandas supports unofficialy a KML driver that you have to enable by hand.

for index, row in gdf.iterrows():
    file_names = row["sites"]
    output_name = f"{file_names}.kml"
    # Create an output path
    outpath = os.path.join(result_folder, output_name)
    # Export the data
    new_kml = gpd.GeoDataFrame(row, row.geometry)
    new_kml.to_file(outpath, driver='KML')

But getting following error:

new_kml = gpd.GeoDataFrame(row, row.geometry)

TypeError: 'Polygon' object is not iterable

1 Answer 1

4

You can use groupby to create a one-row-dataframe for each row and export:

import geopandas as gpd
import numpy as np
import os, fiona

fiona.supported_drivers['KML'] = 'rw' #Enable kml driver
out_folder = r"C:\GIS\data\testdata\KMLs"
df = gpd.read_file(r"C:\GIS\data\testdata\ak_riks_10_fixed.shp")
df["row"] = np.arange(df.shape[0]) #Create a unique row identifier. Not needed if you already have some other unique id

for rownum, subframe in df.groupby("row"): #For each row/rownumber and that row as a dataframe
    filename = os.path.join(out_folder, f"file_{rownum}.kml")    
    subframe.to_file(filename, driver='KML')
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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