Basemap读取shapefile时出现ValueError。

3

我从美国人口普查局下载了一个形状文件地图。它包含了我需要的所有必要信息,但是由于某种原因,我需要的特定地图出现了错误:

Traceback (most recent call last):
  File "C:/Users/Leb/Desktop/Python/Kaggle/mapp.py", line 17, in <module>
    shp_info = m.readshapefile('gis/cb_2014_us_state_5m', 'states', drawbounds=True)
  File "C:\Program Files\Python 3.5\lib\site-packages\mpl_toolkits\basemap\__init__.py", line 2162, in readshapefile
    raise ValueError('readshapefile can only handle 2D shape types')
ValueError: readshapefile can only handle 2D shape types

更具体地说,这些文件(点击这里)给我带来了错误。您可以看到,我下载了5m分辨率的形状文件。
以下是我用来执行命令的代码:
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap as Basemap

m = Basemap(llcrnrlon=-119, llcrnrlat=22, urcrnrlon=-64, urcrnrlat=49,
            projection='lcc', lat_1=33, lat_2=45, lon_0=-95)
shp_info = m.readshapefile('gis/cb_2014_us_state_5m', 'states', drawbounds=True)

问题:

  1. 我需要通过 Fiona 或者 ArcGIS 将其转换为适当的格式吗?
  2. 是否有比 basemap 更好的替代方案?
注:本翻译保留了HTML标签,请在使用时注意不要忽略。

你解决了吗? - Gonzalo Garcia
1个回答

1
问题在于这些cb_文件是shapely 3D PolygonZ对象的列表,而readshapefile需要它们是2D多边形对象,即使Z维度全部为0,就像这些cb_*文件一样。您可以通过去掉Z维度进行转换
我开始使用geopandas作为basemap和其他工具的包装器,并且这就是我如何将它们转换的:
def convert_3D_2D(geometry):
    '''
    Takes a GeoSeries of Multi/Polygons and returns a list of Multi/Polygons
    '''
    import geopandas as gp
    new_geo = []
    for p in geometry:
        if p.has_z:
            if p.geom_type == 'Polygon':
                lines = [xy[:2] for xy in list(p.exterior.coords)]
                new_p = Polygon(lines)
                new_geo.append(new_p)
            elif p.geom_type == 'MultiPolygon':
                new_multi_p = []
                for ap in p:
                    lines = [xy[:2] for xy in list(ap.exterior.coords)]
                    new_p = Polygon(lines)
                    new_multi_p.append(new_p)
                new_geo.append(MultiPolygon(new_multi_p))
    return new_geo

import geopandas as gp
some_df = gp.from_file('your_cb_file.shp')
some_df.geometry = convert_3D_2D(cbsa.geometry)

使用pip install geopandas安装GeoPandas。我认为就是这样了!


这对我没用,from_file在geopandas中不再受支持。 - Gonzalo Garcia

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