1

I have a selection in vector point. I would like to do random sample from it. I am using qgis to do it.

Here is my selection code:

selection=layers_canvas[0].getFeatures(QgsFeatureRequest().setFilterExpression(u'"fitofissio" ILIKE \'%Vereda%\''))
layers_canvas[0].setSelectedFeatures([s.id() for s in selection])

I don't know how to do it. The result of select is on class and it isn't able to use ramdom.sample in it. I tried to do my random sample with this function.

  • If selection is an array of length n and you want a sample of size z, then can you get a sample of indices using sample(xrange(n), z) and simply select those indices from selection? – Cyrille Dec 1 '15 at 15:43
  • My variable selection is a class. See the result above: >>>type(selection) <class 'qgis._core.QgsFeatureIterator'> – Diogo Caribé Dec 1 '15 at 16:17
2

Assuming you want a sample of z elements from n.

As selection is an iterator try this (there's probably a more pythonic way of doing this so feel free to edit):

sel_sample = []
zsample = random.sample(xrange(n), z)
for i in xrange(n):
    if i in zsample:
        sel_sample.append(next())
    else:
        next()
| improve this answer | |
  • 1
    My pythonic way.. sel_sample = [i for i in xrange(n) if i in zsample] – Branco Dec 1 '15 at 18:02
  • Not sure that complies with Simple is better than complex. Readability counts. Sparse is better than dense. while it does say Flat is better than nested. :) Regardless, is it possible to fit the necessary next() portions in the list comprehension? – Cyrille Dec 3 '15 at 14:31
  • I prefer to think of it as Beautiful is better than ugly. I am so used to nested for loops that I just love the flat structure of that. I can see readability problems for those who haven't used it before, but it is a nice optional way to do things. – Branco Dec 3 '15 at 15:14
  • I like it. Is it possible to add the sel_sample.append(next()) and next() code to your list comprehension syntax? – Cyrille Dec 3 '15 at 20:22
  • Oh..my mistake. I am only appending the current iteration to the list. I finally looked up the next() function and that code doesn't do that. I guess I skimmed this a little too quick. I tried some variations to include next() in the loop, but I didn't see a way. – Branco Dec 3 '15 at 20:35

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.