What is the way to get the information contained in the attribute table, say in column 2, row 2 using pyqgis?
To loop over every feature in a layer, use the
getFeatures() generator. This returns an iterator of features (
QgsFeature) in the layer.
for feature in layer.getFeatures(): pass # do something with feature
If you're only interested in a particular feature, instead of all of the features in the layer, you can access it using a
QgsFeatureRequest and it's FID:
fid = 1 # the second feature (zero based indexing!) iterator = layer.getFeatures(QgsFeatureRequest().setFilterFid(fid)) feature = next(iterator)
Once you have a
QgsFeature object you can use the
attributes() method to retrieve the attributes (a.k.a. columns or fields) associated with that feature (a.k.a. row), e.g.:
# get the feature's attributes attrs = feature.attributes() # print the second attribute (note zero based indexing of Python lists) print(attrs)
If you want to index the field by it's name, rather than a number, you need to use the field mappings:
idx = layer.fieldNameIndex('name') print(feature.attributes()[idx])
The field index shouldn't change during the loop, so you only need to call it once.
There is more information and examples in the PyQGIS cookbook: http://www.qgis.org/pyqgis-cookbook/vector.html#iterating-over-vector-layer
You can access feature attributes much more easily by using the
QgsFeature like a
for feature in layer.getFeatures(): name = feature["name"]
I'm not sure which version that came in or if it's always been there.
Thought I would actually add some code, as googling this problem returns this question... most people prefer a quick explanation or a code snippet to a link that leads to a page that has a lot of additonal information.
In order to get the information in a table you would first have to access the layer's features. In my case I put the features in a variable. Then you loop through the features, and for each feature you call its attributes, which can then be printed using their column index. For example, if I would like to get all the values in the second column, then I would do this:
lyr = iface.activeLayer() features = lyr.getFeatures() for feat in features: attrs = feat.attributes() print(attrs)
The answers above only show how to do this for the active layer. I would think, in many cases you might want to find said attribute for a layer that is not the active layers or a layer checked in the Layers window. The code below will get a list of all layers that you have added to your Layers window (regardless if they are checked or active) and find the attribute at row 2, column 2.
from qgis.core import QgsProject layer = QgsProject.instance().mapLayersByName("myLayerName") value = layer.getFeature(2).attribute(2)
Note mapLayersByName returns a list of layers with the given name. I am assuming one exists for this example.