【问题标题】:Getting error KeyError: 'name_long' for 'country' 'records' object "name = country.attributes['name_long']"出现错误 KeyError: 'name_long' for 'country' 'records' object "name = country.attributes['name_long']"
【发布时间】:2018-05-09 16:28:59
【问题描述】:

我从另一个页面“Make colorbar legend in Matplotlib/Cartopy”得到了他的示例,但是当我尝试在 Jupyter Notebook 中运行它时,它会抛出如下错误:

KeyError                                  Traceback (most recent call last)
<ipython-input-3-55c282431f2e> in <module>()
     14 ax = plt.axes(projection=ccrs.Robinson())
     15 for country in shpreader.Reader(countries_shp).records():
---> 16     name = country.attributes['name_long']
     17     num_users = countries[name]
     18     ax.add_geometries(country.geometry, ccrs.PlateCarree(),

KeyError: 'name_long'

请帮忙!代码示例:

import cartopy.crs as ccrs
import cartopy.io.shapereader as shpreader
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

cmap = mpl.cm.Blues
# Countries is a dictionary of {"country_name": number of users}, for example
countries = {"United States": 100, "Canada": 50, "China": 10}

max_users = float(max(countries.values()))
shapename = 'admin_0_countries'
countries_shp = shpreader.natural_earth(resolution='110m', category='cultural', name=shapename)
ax = plt.axes(projection=ccrs.Robinson())
for country in shpreader.Reader(countries_shp).records():
    name = country.attributes['name_long']
    num_users = countries[name]
    ax.add_geometries(country.geometry, ccrs.PlateCarree(),
                facecolor=cmap(num_users/max_users, 1))

plt.savefig('iOS_heatmap.png', transparent=True, dpi=900)

【问题讨论】:

  • 当我记录键时,它有一个键 'name_long': print(sorted(country.attributes.keys())) ['ABBREV', ... 'NAME', 'NAME_ALT', 'NAME_CIAWF'、'NAME_LEN'、'NAME_LONG'、'NAME_SORT'、'NOTE_ADM0'、'NOTE_BRK'、'POP_EST'、...'WOE_NOTE'、'featurecla'、'scalerank']
  • NAME_LONGname_long 不同
  • 自然地球元数据在某些时候发生了变化,键名也被修改了。

标签: python heatmap cartopy


【解决方案1】:

您的 country.attributes 字典/地图没有键 'name_long' 的值。

您的国家是Record,由documentation for shapereader 给出。

记录有属性,这只是一个普通的字典。无论您正在读取什么数据,都没有'name_long' 属性。

您似乎是来自NaturalEarthData 网站的downloading the data。因此,请检查那里实际可用的属性。

根据您的评论,您似乎拥有'NAME_LONG' 键,但是... 'NAME_LONG' != 'name_long'

【讨论】:

    猜你喜欢
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 2018-01-04
    • 2019-07-19
    • 1970-01-01
    • 2012-03-29
    • 2020-04-17
    相关资源
    最近更新 更多