python+gdal 学习记录(一)

学习内容:使用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()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值