6

I have read shapefile into a GeoDataFrame and did some modification to it:

import geopandas as gpd

# Read shapefile into geodataframe
geodf = gpd.read_file("shapefile.shp")

# Do some "pandas-like" modifications to shapefile
geodf = modify_geodf(geodf)

However, I would also like to apply some functionality of osgeo.ogr module on it:

from osgeo import ogr

# Read shapefile into ogr DataSource
ds=ogr.Open("shapefile.shp")

# Do some "gdal/ogr-like" modifications to shapefile
ds = modify_ds(ds)

QUESTION: Is there any way to use or convert an already in-memory shapefile, currently in a form of a GeoDataFrame, as an osgeo.ogr.DataSource directly?

The way I do it so far is to save GeoDataFrame to file with to_file() and then osgeo.ogr.Open() it again, but this seems kind of redundant to me.

Benjamin
  • 11,560
  • 13
  • 70
  • 119
Marjan Moderc
  • 2,747
  • 23
  • 44
  • Why do you need to use both approaches, rather than one of the two? – Benjamin Feb 13 '17 at 14:45
  • 1
    It's just the way how I solved some separate tasks. Some by using ogr, some by using geopandas. The latter I find much more familiar since it is close to pandas. Well, I gave it a shot, thanks for the answer! – Marjan Moderc Feb 13 '17 at 14:51

2 Answers2

8

Yes, it is possible. You can pass the GeoDataFrame into ogr.Open in GeoJson format which is supported OGR vector format. Hence, you don't need to save temporary file into a disk:

import geopandas as gpd
from osgeo import ogr

# Read file into GeoDataFrame
data = gpd.read_file("my_shapefile.shp")

# Pass the GeoDataFrame into ogr as GeoJson
shp = ogr.Open(data.to_json())

# Do your stuff with ogr ...

Hopefully this helps!

htenkanen
  • 196
  • 1
  • 2
  • it did not worked in my case https://gis.stackexchange.com/questions/396995/using-geopandas-geodataframe-in-gdal-grid-for-spatial-interpolation-viz-idw-nea – Abhilash Singh Chauhan May 18 '21 at 21:21
3

No. Only formats supported by OGR can be opened with ogr.Open().

Benjamin
  • 11,560
  • 13
  • 70
  • 119