'How can I export an array of feature collections in geopandas?

I'm attempting to use geopandas to export an array of feature collections to shapefiles. The array structure is as follows:

array of feature collections

I want each feature collection to be exported as it's own shapefile, which I have been able to accomplish by doing the following in geopandas (by using a simple geojson file):

gdf.to_file(filePath)

The above takes any geojson (or in this case a single feature collection) that I hand it & creates a shapefile. The issue is, I want to be able to export multiple feature collections at once (iteratively).

I have also been able to export any number of shapefiles at once with the following:

for num, row in gdf.iterrows():
gdf.iloc[num:num+1,:].to_file(path)

The problem is, the above code only works on a feature collection of features (not on an array of feature collections). Geopandas does not recognize the format of an array of feature collections at all. Has anyone found a workaround for this?



Solution 1:[1]

  • data as an image is not usable in an answer. Have constructed an array of feature collections
  • from this it is simple to iterate over this array, creating a shape file per feature collection
# create a shapefile for each feature collection in array
for fn, feature in enumerate(fca):
    f = Path.cwd().joinpath(f"{fn}/{fn}.shp")
    if not f.parent.exists(): f.parent.mkdir()
    gpd.GeoDataFrame.from_features(feature, crs="epsg:4386").to_file(f)

full code

import numpy as np
import geopandas as gpd
from pathlib import Path

tb = (
    gpd.read_file(gpd.datasets.get_path("naturalearth_lowres"))
    .loc[lambda d: d.iso_a3.eq("BEL")]
    .total_bounds
)
x, y = np.linspace(*tb[[0, 2]], 100), np.linspace(*tb[[1, 3]], 100)

# construct an array of feature collections
fca = [
    {
        "type": "FeatureCollection",
        "features": [
            {
                "type": "Feature",
                "properties": {"identifier": f"{i}_{j}"},
                "geometry": {
                    "type": "Point",
                    "coordinates": [
                        np.random.choice(x, 1)[0],
                        np.random.choice(y, 1)[0],
                    ],
                },
            }
            for j in range(5)
        ],
    }
    for i in range(3)
]

# create a shapefile for each feature collection in array
for fn, feature in enumerate(fca):
    f = Path.cwd().joinpath(f"{fn}/{fn}.shp")
    if not f.parent.exists(): f.parent.mkdir()
    gpd.GeoDataFrame.from_features(feature, crs="epsg:4386").to_file(f)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rob Raymond