学习内容:使用OGR过滤数据
记录《python 地理数据处理》书中的内容
一、属性过滤条件
- lyr.SetAttributeFilter(“continent = ‘Asia’”)筛选出符合的要素,获取个数
from osgeo import ogr
from ospybook.vectorplotter import VectorPlotter
import ospybook as pb
# 读取图层
ds=ogr.Open(r"C:\Users\Administrator\Desktop\osgeo_train\global")
lyr=ds.GetLayer('ne_50m_admin_0_countries')
# 绘制空间数据
vp=VectorPlotter(True)
vp.plot(lyr,fill=False)
# 查看亚洲包含多少要素
asia=lyr.SetAttributeFilter("continent = 'Asia'")
# asia 为0时,表示查询语句被执行成功
print(asia)
# 总共有多少个亚洲
count_asia=lyr.GetFeatureCount()
print(count_asia)
# 清除属性过滤条件
#lyr.SetAttributeFilter(None)
二、空间过滤条件
- 用于作为空间过滤条件的要素或者坐标,必须与要筛选的图层具有同样的空间参考系统。
#选取德国城市
#打开数据源文件夹获取国家边界图层,然后使用属性过滤条件筛选出德国,并获得对应的要素记录和几何对象
#然后再使用德国边界,根据空间过滤条件,筛选出居住区图层中的德国城市。
from osgeo import ogr
from ospybook.vectorplotter import VectorPlotter
import ospybook as pb
# 打开图层
ds=ogr.Open(r"C:\Users\Administrator\Desktop\osgeo_train\global")
lyr=ds.GetLayer('ne_50m_admin_0_countries')
vp=VectorPlotter(True)
vp.plot(lyr,fill=False)
# 根据属性过滤条件筛选出德国
""" 属性过滤条件筛选后会返回一个要素,lyr.GetNextFeature()获得这个要素
Clone() 克隆这个要素,这样即使要素在内存中被删除后,仍然可以使用"""
country=lyr.SetAttributeFilter("name = 'Germany'")
feat=lyr.GetNextFeature()
germany=feat.geometry().Clone()
# 加载城市图层,并绘制
city_lyr=ds.GetLayer('ne_50m_populated_places')
#vp.plot(city_lyr,'y.')
# 根据空间过滤条件,筛选出德国的城市
country_filter=city_lyr.SetSpatialFilter(germany)
country_count=city_lyr.GetFeatureCount()
print(country_count)
vp.plot(city_lyr,'bo')
# 找出德国人口超过100万的城市
country_100 = city_lyr.SetAttributeFilter('pop_min > 1000000')
country_100_count = city_lyr.GetFeatureCount()
# 找世界上有多少人口超过100万的城市
# 注意属性过滤条件仍然有效
world_country_100 = city_lyr.SetSpatialFilter(None)
world_country_100_count = city_lyr.GetFeatureCount()