我试图将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 文件中。 - José L. Patiño