2

I've been getting into PyQGIS, and as a start I want to select the first instance of pair values of a point layer (start and end of a street), identified by the same integer, I got this, but it doesn't work:

("int_id" is the value that is the same for the start and end points)

cap = iface.activeLayer()
feat = cap.getFeatures()

frm = []

for f in feat:
    if f["int_id"] not in frm:
        frm.append(f.id())

cap.select(frm)

I need to create lines from these points (start and end), I haven't found a way to create them in PyQGIS, but I found point connector plugin that could at least create the streets that are a straight line, but first I need to separate the start points from the end points.

2 Answers 2

1

You can use collections.Counter to find which ID:s occur twice:

from collections import Counter
cap = iface.activeLayer()
feat = cap.getFeatures()
fieldname = 'int_id'

cnt = Counter([f[fieldname] for f in feat]) #Create dictionary of int_id and their counts
twice = [k for k,v in cnt.items() if v==2] #cnt.items() if python3/qgis3, cnt.iteritems() py2/qgis2

expr = '"{0}"={1}'.format(fieldname, twice[0])
cap.selectByExpression(expr)

enter image description here

0

The below assumes that only the init_id of the first and last points are equal

from collections import Counter
from itertools import groupby
from qgis.core import *

cap = iface.activeLayer()
feat = cap.getFeatures()

#create a list conatining all features
frm = []

#assuming field int_id is in the first column=0
for f in feat:
    frm.append(f[0])


print (frm)

#now creating new list containing the 2 points
list2=[]
for k,v in Counter(frm).items():
    if v>1:
        list2.append(k) 

print ("list2 =", list2)
#finally selecting the 2 points with same id
for m in cap.getFeatures():
    if m[0] in list2:
        cap.select(m.id())

#####END

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.