直接将Geopandas数据帧导出到压缩的形状文件

2024-09-27 00:19:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将Geopandas数据帧保存到一个直接写入压缩文件夹的shapefile中

任何shapefile用户都知道,shapefile不是单个文件,而是要一起读取的文件集合。因此,调用myGDF.to_file(filename='myshapefile.shp', driver='ESRI Shapefile')不仅会创建myshapefile.shp,还会创建myshapefile.prjmyshapefile.dbfmyshapefile.shxmyshapefile.cpg。这可能就是为什么我在这里努力获取语法的原因

例如考虑一个虚拟GEOPANDA数据文件,如:

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)

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

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

但它没有起作用

然后我尝试了以下方法(在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'))

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

如何将Geopandas数据帧直接写入压缩的形状文件


Tags: 文件toimport文件夹dataasdriverzip
2条回答

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

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)

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

myGDF.to_file(filename='myshapefile.zip', driver='ESRI Shapefile')

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

相关问题 更多 >

    热门问题