7

I'd like to save the R-tree spatial index generated by GeoPandas to disk. GeoPandas automatically generates an index for each shape (points in this case) in the dataframe. I'm attempting to create a new index using the R-trees built in built-in disk serialization, but not sure how to build it up to match the original dataframe. I've made a hack by simply iterating over the number of shapes and adding bounds... this seems to work for my purposes but am quite sure this is not the correct approach.

Apologies for not taking the time to fully understanding how R-trees work. I borrowed from this post Saving python Rtree spatial index to file? and found this discussion https://github.com/geopandas/geopandas/issues/426

import numpy as np, pandas as pd, geopandas as gpd
from shapely.geometry import Point
from rtree.index import Index

lats = np.arange(10, 20, 1)
lons = np.arange(60, 80, 2)
df        = pd.DataFrame({'lat': lats, 'lon': lons})
df['geo'] = df.apply(lambda df: Point(df['lon'], df['lat']), axis=1)
gdf       = gpd.GeoDataFrame(df, geometry='geo', crs='EPSG:4326')
sidx      = gdf.sindex
bounds    = sidx.bounds

idx       = Index('path')
for sid in range(sidx.get_size()):
    idx.insert(1, sidx.bounds)
idx.close()
1
  • I thought it should be possible to save a spatial index in the GeoDataFrame in the GeoPackage format. When I add a layer from a .gpkg file to QGIS, I can verify that it has a spatial index. And if I view the .gpkg file in DB Browser for SQLite, I can see 4 tables with the prefix Rtree. Yet, when I open that same layer with GeoPandas, gdf.has_sindex = False. I suppose that the type of spatial index that GeoPandas uses is different, or that it is incapable of reading it from the GeoPackage file.
    – Matt H
    Apr 4, 2023 at 8:11

0

Your Answer

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

Browse other questions tagged or ask your own question.