4

I am trying to extract only three polygons from my attribute table from a vector layer. The column which contains the values I want is called "ID".

import processing

layer = r'C:\mypath....\mylayer.shp'
output = r'C:\mypath....\out.shp'

parameters = {'INPUT': layer, 'FIELD':'ID', 'OPERATOR':'7', 'VALUE': ['08008:0:0:8:81:3' and '08008:0:0:8:81:5' and '08008:0:0:8:89:1'], 'OUTPUT': output}
feedback = QgsProcessingFeedback()

processing.runAndLoadResults('native:extractbyattribute',
                            parameters,
                            feedback=feedback
                            )

This code gives me a new layer with the same attribute table as the original. I know the problem is related to 'VALUE' list, but don't know how to write the correct one.

2 Answers 2

6

Use extract by expression with parentheses and escape backslashes in front of each values single quote:

input = r'/home/bera/GIS/Data/testdata/ak_riks.shp'
output = r'/home/bera/Desktop/gistemp/ok_jl_riks_extracted.shp'

processing.run("native:extractbyexpression", 
    {'INPUT':input,
    'EXPRESSION':' "KOM_KOD" IN( \'2510\' , \'2523\' , \'2584\' )',
    'OUTPUT':output})

I executed the command manually then pressed Ctrl+Alt+H to see the syntax

5

You can use GRASS > Vector > v.extract tool (see documentation).

layer = r'C:\mypath....\mylayer.shp'
output = r'C:\mypath....\out.shp'

processing.runAndLoadResults("grass7:v.extract",
                             {'input': layer,
                              'where': "ID IN (0, 1, 2, 3)", # specify IDs
                              'type': [0,1,3,4,5],
                              'output': output})

If field type of ID is string, us this for where:

'where':"ID IN ('0', '1', '2', '3')"

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.