【发布时间】:2021-07-09 06:58:42
【问题描述】:
我正在尝试将 Geopandas 数据框保存到直接写入压缩文件夹的 shapefile 中。
任何 shapefile 用户都知道,shapefile 不是单个文件,而是要一起读取的文件集合。所以调用myGDF.to_file(filename='myshapefile.shp', driver='ESRI Shapefile') 不仅会创建myshapefile.shp,还会创建myshapefile.prj、myshapefile.dbf、myshapefile.shx 和myshapefile.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)
我看到有人使用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 DataFrame 编写为压缩的 shapefile?
【问题讨论】:
-
你的
myGDF.to_file(...方法将返回None,而zipf.write的输入必须是一个字符串,所以这永远不会起作用。我也怀疑您是否使用该代码在 zip 文件中写入了任何文件。
标签: python zipfile shapefile geopandas