python - basemap 读取shapefile ValueError

标签 python matplotlib matplotlib-basemap

我从 US Census 下载了一张 map 以 shapefile 格式。它具有我需要的所有必需信息,但由于某种原因,有一张我需要的特定 map ,它给了我这个错误:

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

更具体地说 these一组文件给我错误。如您所见,我下载了 5m 分辨率的 shapefile。

这是我用来执行命令的代码:

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 更好的替代方案?

最佳答案

问题是这些 cb_ 文件是 3D PolygonZ 对象的列表,而 readshapefile 需要它们是 2D Polygon 对象,即使 Z 维度全为 0,如这些 cb_*文件。你可以convert them by stripping the Z dimension .

我开始使用 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。我认为应该是这样!

关于python - basemap 读取shapefile ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33417764/

相关文章:

python - 为特定的 IPython 配置文件选择 matplotlib 后端

list - 使用 Python (Google Maps API) 从地理编码结果列表中提取纬度/经度

python - 如何为 matplotlib 的 drawgreatcircle 函数制作动画?

python - 从数据框中的每一行中删除日期时间字符串

python - 如何按方括号之间的内容进行数字排序

python - matplotlib 中的中心原点

python - 在不使用 xticks 的情况下设置二维等高线图的轴值

python - Spyder 导入 basemap 时出现 PROJ_LIB 错误

python - 为什么不建议在conda基础环境中安装额外的包?它的目的是什么?

python - 如何查找列表中的前一个元素?