- QGIS Python Programming Cookbook
- Joel Lawhead
- 330字
- 2021-07-23 19:48:53
Examining vector layer attributes
A true GIS layer contains both spatial geometry and database attributes. In this recipe, we'll access a vector point layer's attributes in PyQGIS. We'll use a file-based layer from a shapefile, but once a layer is loaded in QGIS, every vector layer works the same way.
Getting ready
Once again, we'll use the same New York City Museums layer from the Loading a vector layer from a file recipe in this chapter. You can download the layer from https://geospatialpython.googlecode.com/svn/NYC_MUSEUMS_GEO.zip.
Unzip that file and place the shapefile's contents in a directory named nyc
within your qgis_data
directory, within your root or home directory.
How to do it...
In the following steps, we'll load the layer, access the features
iterator, grab the first feature, and then view the attributes as a Python list:
- First, load the shapefile as a vector layer:
layer = QgsVectorLayer("/qgis_data/nyc/NYC_MUSEUMS_GEO.shp", "New York City Museums", "ogr")
- Next, get the features iterator:
features = layer.getFeatures()
- Now, grab the first feature from the iterator:
f = features.next()
- Finally, examine the attributes as a Python list:
f.attributes()
- Verify that the Python console's output resembles the following list:
[u'Alexander Hamilton U.S. Custom House', u'(212) 514-3700', u'http://www.oldnycustomhouse.gov/', u'1 Bowling Grn', NULL, u'New York', 10004.0, -74.013756, 40.703817]
How it works...
Examining attributes is consistent with accessing the point values of a layer's geometry. Note that all string attribute values are returned as unicode strings, which is the case for all QGIS strings. Unicode allows the internationalization (that is, translation) of QGIS for other languages besides English.
There's more...
The attribute values don't mean much without the knowledge of what those values represent. You will also need to know the fields. You can get the fields as a list by accessing the fields
iterator and calling the name()
method for each field. This operation is easily accomplished with a Python list comprehension:
[c.name() for c in f.fields().toList()]
This example returns the following result:
[u'NAME', u'TEL', u'URL', u'ADRESS1', u'ADDRESS2', u'CITY', u'ZIP', u'XCOORD', u'YCOORD']
- C語(yǔ)言程序設(shè)計(jì)教程(第2版)
- Learning Informatica PowerCenter 10.x(Second Edition)
- R的極客理想:工具篇
- Oracle BAM 11gR1 Handbook
- TradeStation交易應(yīng)用實(shí)踐:量化方法構(gòu)建贏家策略(原書第2版)
- Python數(shù)據(jù)結(jié)構(gòu)與算法(視頻教學(xué)版)
- Python Web數(shù)據(jù)分析可視化:基于Django框架的開發(fā)實(shí)戰(zhàn)
- Linux Shell核心編程指南
- 詳解MATLAB圖形繪制技術(shù)
- MySQL數(shù)據(jù)庫(kù)應(yīng)用實(shí)戰(zhàn)教程(慕課版)
- React and React Native
- Laravel 5.x Cookbook
- Learning Rust
- Sony Vegas Pro 11 Beginner’s Guide
- Learn Spring for Android Application Development