使用Cartopy ShapeReader#
Cartopy提供了基于 pyshp 模块可提供对标准载体数据集的简单、编程的访问。
Cartopy对pyshp的包装具有纯Python的好处,因此易于安装且极其便携。然而,对于重型Shapetime I/O Fiona 和 GeoPandas 强烈推荐。
ShapeReader功能的详细API可在 documentation
ShapFile获取的助手功能#
Cartopy提供了一个接口,用于访问常用数据,例如 GSHHS 数据集和来自 NaturalEarthData 网站这些接口允许用户以编程方式定义数据,如果数据不存在于磁盘上,则将从适当的来源检索它(通常通过从互联网下载数据)。目前可用的接口有 natural_earth()
和 gshhs()
.
使用Shape Reader#
我们可以使用从https://www.naturalearthdata.com/downloads/110m-cultural-vectors/110m-admin-0-countries/上找到的自然地球获取国家数据集 natural_earth()
功能:
import cartopy.io.shapereader as shpreader
shpfilename = shpreader.natural_earth(resolution='110m',
category='cultural',
name='admin_0_countries')
从这里,我们可以利用 Reader
要获取形状文件中的第一个国家:
reader = shpreader.Reader(shpfilename)
countries = reader.records()
country = next(countries)
我们可以通过 Record.attributes
属性:
>>> print type(country.attributes)
<type 'dict'>
>>> print sorted(country.attributes.keys())
['abbrev', ..., 'name_long', ... 'pop_est', ...]
我们现在可以找到5个人口最少的国家:
reader = shpreader.Reader(shpfilename)
# define a function which returns the population given the country
population = lambda country: country.attributes['pop_est']
# sort the countries by population and get the first 5
countries_by_pop = sorted(reader.records(), key=population)[:5]
我们可以用它打印
>>> ', '.join([country.attributes['name_long']
... for country in countries_by_pop])
'Western Sahara, French Southern and Antarctic Lands, Falkland Islands, Antarctica, Greenland'
Exercises :
SHP.1 :重复最后一个例子,在形状文件中显示4个人口最多的非洲国家。
提示:查看可能的属性以找出一个国家属于哪个大陆。
答:
Democratic Republic of the Congo, Egypt, Ethiopia, NigeriaSHP.2 :使用国家/地区形状文件,查找人口最多的国家/地区(按“Name_long”的第一个字母分组)。
提示:
itertools.groupby()
可以帮助分组。答:
A Argentina B Brazil C China D Democratic Republic of the Congo E Ethiopia F France G Germany H Hungary I India J Japan K Kenya L Lao PDR M Mexico N Nigeria O Oman P Pakistan Q Qatar R Russian Federation S South Africa T Turkey U United States V Vietnam W Western Sahara Y Yemen Z Zimbabwe