如何从Fiona获取字典格式输出而非fiona.model.Feature对象
问题描述
我正在遵循Fiona官方文档中的示例,但使用的是弗吉尼亚州的地块shp文件(压缩包约1GB,解压后约1.8GB)。
我编写了如下代码:
fiava = fiona.open("VirginiaParcel.shp/VirginiaParcel.shp", layer='VirginiaParcel')
通过fiava.schema可以获取到要素结构:
# {'properties': {'FIPS': 'str:8', # 'LOCALITY': 'str:64', # 'PARCELID': 'str:64', # 'PTM_ID': 'str:64', # 'LASTUPDATE': 'date', # 'VGIN_QPID': 'str:50'}, # 'geometry': 'Polygon'}
到目前为止一切正常,但当我执行fiava[0]时,得到的是Feature对象而非预期的字典格式:
## <fiona.model.Feature at 0x7f2fd582aa10>
文档中显示的输出应为字典格式:
{'geometry': {'coordinates': [[(-4.663611, 51.158333), (-4.669168, 51.159439), (-4.673334, 51.161385), (-4.674445, 51.165276), (-4.67139, 51.185272), (-4.669445, 51.193054), (-4.665556, 51.195), (-4.65889, 51.195), (-4.656389, 51.192215), (-4.646389, 51.164444), (-4.646945, 51.160828), (-4.651668, 51.159439), (-4.663611, 51.158333)]], 'type': 'Polygon'}, 'id': '1', 'properties': OrderedDict([('CAT', 232.0), ('FIPS_CNTRY', 'UK'), ('CNTRY_NAME', 'United Kingdom'), ('AREA', 244820.0), ('POP_CNTRY', 60270708.0)]), 'type': 'Feature'}
如果通过schema指定键逐个获取数据,效率很低:
fiava[0]['properties']['FIPS'] ## 51149
即使执行fiava[0].items(),得到的也只是ItemsView。请问我忽略了什么?
解决方案
这是因为你使用的是新版Fiona——旧版默认返回字典格式的要素,而新版改用了fiona.model.Feature对象来提供更丰富的方法和属性,你参考的文档可能是针对旧版本的内容。
要获取字典格式的数据,有几种方式:
- 单个要素转换为字典:直接对Feature对象调用
dict()方法
feature_dict = dict(fiava[0])
- 遍历所有要素并转换:遍历数据集时逐个转换
for feature in fiava: feature_dict = dict(feature) # 在这里处理字典格式的要素数据
- 直接获取字典迭代器:使用
records()方法,返回的迭代器会直接产出字典格式的要素
with fiona.open("VirginiaParcel.shp/VirginiaParcel.shp", layer='VirginiaParcel', mode='r') as fiava: for record in fiava.records(): print(record) # record就是字典格式
内容的提问来源于stack exchange,提问作者Dean MacGregor
相关产品推荐
相关产品推荐

