将 Geopandas 数据框直接导出到压缩的 shapefile

saQ*_*ist 6 python shapefile zipfile geopandas

我正在尝试将 Geopandas 数据框保存到直接写入压缩文件夹的 shapefile 中。

任何 shapefile 用户都知道,shapefile 不是单个文件,而是旨在一起读取的文件集合。所以呼吁 myGDF.to_file(filename='myshapefile.shp', driver='ESRI Shapefile')不仅创造myshapefile.shp而且myshapefile.prjmyshapefile.dbfmyshapefile.shxmyshapefile.cpg。这可能就是我努力在这里获得语法的原因。

例如,考虑一个虚拟的 Geopandas 数据框,例如:

import pandas as pd
import geopandas as gpd
from shapely.geometry import Point

data = pd.DataFrame({'name': ['a', 'b', 'c'],
    'property': ['foo', 'bar', 'foo'],
        'x': [173994.1578792833, 173974.1578792833, 173910.1578792833],
        'y': [444135.6032947102, 444186.6032947102, 444111.6032947102]})
geometry = [Point(xy) for xy in zip(data['x'], data['y'])]
myGDF = gpd.GeoDataFrame(data, geometry=geometry)
Run Code Online (Sandbox Code Playgroud)

我看到人们使用gzip,所以我尝试:

import geopandas as gpd
myGDF.to_file(filename='myshapefile.shp.gz', driver='ESRI Shapefile',compression='gzip')
Run Code Online (Sandbox Code Playgroud)

但它没有用。

然后我尝试了以下操作(在 Google Colab 环境中):

import zipfile
pathname = '/content/'
filename = 'myshapefile.shp'
zip_file = 'myshapefile.zip'
with zipfile.ZipFile(zip_file, 'w') as zipf:
   zipf.write(myGDF.to_file(filename = '/content/myshapefile.shp', driver='ESRI Shapefile'))
Run Code Online (Sandbox Code Playgroud)

但它只将.shp文件保存在 zip 文件夹中,而其余部分则写入 zip 文件夹旁边。

如何直接将 Geopandas DataFrame 编写为压缩的 shapefile?

Gre*_*ald 8

只需用作zip文件扩展名,保留驱动程序的名称:

myGDF.to_file(filename='myshapefile.shp.zip', driver='ESRI Shapefile')
Run Code Online (Sandbox Code Playgroud)

这应该适用于 GDAL 3.1 或更高版本。

  • 我得到一个名为“myshapefile.zip”的(非压缩)文件夹。GDAL 3.3.1 (9认同)

fis*_*x44 6

像这样的东西对你有用 - 将 shapefile 转储到一个新的临时目录中,然后压缩该临时目录中的所有内容。

import tempfile
import zipfile
from pathlib import Path

with tempfile.TemporaryDirectory() as temp_dir:

    temp_dir = Path(temp_dir)

    # geodataframe.to_file(str(d / "myshapefile.shp"))
    with open(temp_dir / "a.shp", "w") as _f:
        _f.write("blah")
    with open(temp_dir / "a.prj", "w") as _f:
        _f.write("blah")

    with zipfile.ZipFile('myshapefile.zip', 'w') as zipf:
        for f in temp_dir.glob("*"):
            zipf.write(f, arcname=f.name)
Run Code Online (Sandbox Code Playgroud)