通常情况下,我们发现自己使用的空间数据比我们需要的更精细。例如,我们可能有关于次国家单位的数据,但我们实际上对研究各国一级的模式感兴趣。就是得到上一个等级的数据,话不多说,直接看例子:
world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
world = world[['continent', 'geometry']]
continents = world.dissolve(by='continent')
continents.plot()
continents.head()
合并数据的方式有两种:属性链接和空间链接,我们直接看例子。
1 world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres')) 2 cities = geopandas.read_file(geopandas.datasets.get_path('naturalearth_cities')) 3 country_shapes = world[['geometry', 'iso_a3']] 4 country_names = world[['name', 'iso_a3']] 5 # For spatial join 6 countries = world[['geometry', 'name']] 7 countries = countries.rename(columns={'name':'country'})
上述的在打开数据,下面进行属性链接
country_shapes.head() Out[7]: geometry iso_a3 0 POLYGON ((61.21081709172574 35.65007233330923,... AFG 1 (POLYGON ((16.32652835456705 -5.87747039146621... AGO 2 POLYGON ((20.59024743010491 41.85540416113361,... ALB 3 POLYGON ((51.57951867046327 24.24549713795111,... ARE 4 (POLYGON ((-65.50000000000003 -55.199999999999... ARG country_names.head() Out[8]: name iso_a3 0 Afghanistan AFG 1 Angola AGO 2 Albania ALB 3 United Arab Emirates ARE 4 Argentina ARG # Merge with `merge` method on shared variable (iso codes): country_shapes = country_shapes.merge(country_names, on='iso_a3') country_shapes.head() Out[10]: geometry ... name 0 POLYGON ((61.21081709172574 35.65007233330923,... ... Afghanistan 1 (POLYGON ((16.32652835456705 -5.87747039146621... ... Angola 2 POLYGON ((20.59024743010491 41.85540416113361,... ... Albania 3 POLYGON ((51.57951867046327 24.24549713795111,... ... United Arab Emirates 4 (POLYGON ((-65.50000000000003 -55.199999999999... ... Argentina
空间链接的例子:
# One GeoDataFrame of countries, one of Cities. # Want to merge so we can get each city's country. In [11]: countries.head() Out[11]: geometry country 0 POLYGON ((61.21081709172574 35.65007233330923,... Afghanistan 1 (POLYGON ((16.32652835456705 -5.87747039146621... Angola 2 POLYGON ((20.59024743010491 41.85540416113361,... Albania 3 POLYGON ((51.57951867046327 24.24549713795111,... United Arab Emirates 4 (POLYGON ((-65.50000000000003 -55.199999999999... Argentina In [12]: cities.head() Out[12]: name geometry 0 Vatican City POINT (12.45338654497177 41.90328217996012) 1 San Marino POINT (12.44177015780014 43.936095834768) 2 Vaduz POINT (9.516669472907267 47.13372377429357) 3 Luxembourg POINT (6.130002806227083 49.61166037912108) 4 Palikir POINT (158.1499743237623 6.916643696007725) # Execute spatial join In [13]: cities_with_country = geopandas.sjoin(cities, countries, how="inner", op='intersects') In [14]: cities_with_country.head() Out[14]: name ... country 0 Vatican City ... Italy 1 San Marino ... Italy 192 Rome ... Italy 2 Vaduz ... Austria 184 Vienna ... Austria [5 rows x 4 columns]