2

I want to automatically count features in my opened layers, and add the result in the layer name, with pyqgis. I can do it with this code :

layers = QgsProject.instance().mapLayers().values()
for layer in layers:
   fc = layer.featureCount()
   fc = str(fc)
   layer.setName(layer.name()+" ["+fc+"]")

However, it does count features in each layer, but not in each renderer category when a layer have a categorized style. I was trying something like this just to print the result :

for layer in layers:
    renderer = layer.renderer()
    renderert = renderer.type()
    if renderert == "categorizedSymbol":
        for cat in renderer.categories():
            print(cat.label+cat.featureCount())

But i get an "AttributeError: 'QgsRendererCategory' object has no attribute 'featureCount'"

Do you know how to apply the featureCount() function to layers and categories?

2 Answers 2

3

From this answer, is this code below a nicer solution ?

I just use the builtin layer function Show feature count :

layers = QgsProject.instance().mapLayers().values()
root = QgsProject.instance().layerTreeRoot()
for layer in layers:
    if layer.type() == QgsMapLayer.VectorLayer:
        myLayerNode = root.findLayer(layer.id())
        myLayerNode.setCustomProperty("showFeatureCount", True)
1
  • Thank you, that's exactly what i needed. It counts the features of layers and categories, and add the result in their name.
    – Cupain
    Nov 27, 2019 at 13:27
3

You can use collections.Counter.

from collections import Counter
layer = iface.activeLayer() # My layer 
field_categorized = 'category' # My categorized field 
c = Counter([feature[field_categorized] for feature in layer.getFeatures()]) # Loop on features of the layer 

# Result 
print(c)
Counter({0: 67, 1: 34})
1
  • Thank you for the answer! I think it's ok to get one result for one particular category. But J. Monticolo's answer is more simple and add the result to the layer name
    – Cupain
    Nov 27, 2019 at 13:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.