使用 GeoDataFrame 作为 osgeo.ogr 数据源

Mar*_*erc 4 python ogr geopandas

我已将 shapefile 读入 aGeoDataFrame并对其进行了一些修改:

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)
Run Code Online (Sandbox Code Playgroud)

但是,我还想osgeo.ogr在其上应用模块的一些功能:

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)
Run Code Online (Sandbox Code Playgroud)

问题:有什么方法可以直接使用或转换已在内存中的 shapefile,目前采用 GeoDataFrame 的形式osgeo.ogr.DataSource

到目前为止,我这样做的方法是将 GeoDataFrame 保存到文件中to_file(),然后osgeo.ogr.Open()再次保存,但这对我来说似乎有些多余。

小智 7

对的,这是可能的。您可以将 GeoDataFrame 以支持 OGR 矢量格式的 GeoJson 格式传递到 ogr.Open 中。因此,您不需要将临时文件保存到磁盘中:

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 ...
Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助!