I've been trying in vain to use the field calculator in QGIS 2.8 to count the combinations of two attributes in two separate columns.

First column is called "Alds_klass" and second is called "bygn_klass". I want to count the different combinations of the two columns, not the sum, but the number of each combination.

enter image description here


If you're ready NOT to use the field calculator i would create a virtual layer based on the following query (to adapt) :

select count(*) as tot, col_a, col_b from my_table
group by col_a, col_b
order by tot desc

Which would be "dynamic" ...

(implies to use a newer QGIS version...)

| improve this answer | |

You can use the tool "Statistics by categories" (in the processing toolbox in QGIS 3.2)

enter image description here

enter image description here

enter image description here

| improve this answer | |

Create a new column and fill it with a case when or if clause looping over all possible values. Assign each combination a different letter of the alphabet, and then do a statistical analysis of the new column.

Or just load it into a database.

| improve this answer | |

If you want to populate Count_Al_b with the total count of combinations Alds_class+bygn_class you can use collections.Counter:

...where elements are stored as dictionary keys and their counts are stored as dictionary values.

print 'start'
from qgis.core import *
import qgis.utils
from qgis.core import QgsVectorLayer
from collections import Counter

alds = "Alds_klass"
bygn = "bygn_klass"
totcount = "Count_Al_b"
datafile = '/media/bera/my_03.shp' #Change

layer = QgsVectorLayer(datafile, 'temp', 'ogr')
c = Counter([(f[alds],f[bygn]) for f in layer.getFeatures()])

it = layer.getFeatures()
for feat in it:
    #layer.fields().indexFromName(totcount) python 3/QGIS 3
print 'stop'

Example: enter image description here

| improve this answer | |

I would use the field calculator to create a virtual field containing the concatenation (i.e. combination) of your two fields, like this:

enter image description here

The underscore '_' ist just for better readabilty and does not affect the result.

Then use the 'Show statistical summary' button (the button with the big sigma):

enter image description here

Herein select your layer and the virtual field you just created, and under Count (distinct) you will find the count of your columns combinations:

enter image description here

The virtual field and the tool do dynamically refresh when data changes.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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