Friday, 11 August 2017

Summarizing Fields based on content in QGIS?


already read many answers for similar questions, but i didnt find a solution for my problem. Dont know how to start.


Problem: shp with about 50 fields. Each field contain NULL, 1 or 2. Now i need two new fields. One containing the number of fields with "1", the other with "2".


I am using QGis 2.16.2 and 2.14; OS Win10


I'm trying @Joseph's solution, add the hint @kyle reed and make some modifications to start as an expression:


@qgsfunction(args='auto', group='Custom')
def R1func(feature, parent):
lists = []
layer = qgis.utils.iface.activeLayer()
for feat in layer.getFeatures():

f = feat.fields()
num = f.count()
for i in range(num):
if feat[i] == 2:
lists.append(i)

return len(set(lists))

and also try a short version


@qgsfunction(args='auto', group='Custom')

def R2func(feature, parent):
lists = []
layer = qgis.utils.iface.activeLayer()
for feat in layer.getFeatures():
lists.append(feat.fields())

return lists.count(2)

Version 1 returns for every row 60 (for number 1) or 37 (for number 2) Version 2 returns 0


Maybe i make a mistake.




Answer



Using a bit of python, you could obtain the number of fields which contains a specific value. Use the following in the Python Console and change the value:


lists = []
layer = iface.activeLayer()
for feat in layer.getFeatures():
f = feat.fields()
num = f.count()
for i in range(num):
# Look for fields with a value of 1
if feat[i] == 1:

lists.append(i)

print len(set(lists))

Then use the printed value as the expression when adding a new field. Repeat for your second value.




EDIT:


If you want to count the values in each row, you could use the following in the Function Editor of the Field Calculator:


from qgis.core import *
from qgis.gui import *

import qgis

@qgsfunction(args='auto', group='Custom')
def counting(value1, feature, parent):
layer = qgis.utils.iface.activeLayer()
return feature.attributes().count(value1)

Then type as the expression:


counting(1)


This will count all values which equal 1 for each row in each field.




Note that if you use it twice, it will also count the values in the new field that was created previosuly, in which case you would have to subtract all values greater than zero by one.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...