无法使用GeoPandas打开shape文件。

7

我好像无法打开我从(http://www.vdstech.com/usa-data.aspx)下载的zip3.zip形状文件。

这是我的代码:

import geopandas as gpd
data = gpd.read_file("data/zip3.shp")

这让我出现了错误:
CPLE_AppDefinedError: b'Recode from CP437 to UTF-8 failed with the error: "Invalid argument".'

这个情况下非常相关的帖子(也许有重复的吗?) - DarkCygnus
4个回答

4

看起来这个 shapefile 没有关联一个 cpg 文件来指定编码方式,然后采用默认系统编码方式也无法处理 .dbf 文件。你可以尝试使用以下方法打开文件:

data = gpd.read_file("data/zip3.shp", encoding="utf-8")

geopandas 依赖于 fiona 来读取 shapefile,你可能需要升级你的 fiona 版本才能使其正常工作;可以参考这里的一些讨论 here


4
根据我在this问题上的answer, 看起来您的数据集包含非UTF字符。如果您遇到类似问题,使用encoding-"utf-8"可能无法解决问题,因为Fiona的open()调用仍将失败。
如果其他解决方案不起作用,我提出的两个解决方案是:
  1. Open your shapefile on a GIS editor (like QGis), then save it again making sure you select the Encoding option to "UTF-8". After this you should have no problem when calling gpd.read_file("data/zip3.shp").

  2. You can also achieve this format change in Python using GDAL, by reading your shapefile and saving it again. This will effectively change the encoding to UTF-8, as this is the default encoding as indicated in the docs for the CreateDataSource() method. For this try the following code snippet:

    from osgeo import ogr
    
    driver = ogr.GetDriverByName("ESRI Shapefile")
    ds = driver.Open("nbac_2016_r2_20170707_1114.shp", 0) #open your shapefile
    #get its layer
    layer = ds.GetLayer()
    
    #create new shapefile to convert
    ds2 = driver.CreateDataSource('convertedShape.shp')
    #create a Polygon layer, as the one your Shapefile has
    layer2 = ds2.CreateLayer('', None, ogr.wkbPolygon)
    #iterate over all features of your original shapefile
    for feature in layer:
       #and create a new feature on your converted shapefile with those features
       layer2.CreateFeature(feature)
    #proper closing
    ds = layer = ds2 = layer2 = None 
    

1
谢谢。我能够按照您的建议使用QGis。 - Fred R.

1

由于您可能已经安装了GDAL,我建议使用CLI将文件转换为UTF-8:

ogr2ogr output.shp input.shp -lco ENCODING=UTF-8

对我来说,它的效果非常好。它比QGIS快得多,并且可以在集群环境中使用。我也在这里发布了这个答案。在geopandas中指定编码对我没有起作用。


0
也许该文件依赖于其他文件。 我遇到了同样的问题,当我复制了这个shapefile所依赖的其他文件时,代码正确运行,但要求安装另一个名为descartes的包。当我安装了这个包后,代码就正确运行了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接