5

With PyQGIS.I am trying to create a new vector layer by filtering another vector layer based on its attributes. Here is the code that I am using:

fn = r"C:/path/file.shp"
layer = QgsVectorLayer(fn, '', 'ogr')
features_layer = layer.getFeatures()

new_list = []
for feat in features_layer:
    attrs_layer = feat.attributes()
    if (boolean criteria for filtering on the attributes of the existing layer):
       new_list.append(attrs_layer)

file_path = r"C:/path/folder"
new_layer = QgsVectorLayer(file_path, '', "ogr")
provider = new_layer.dataProvider()
provider.addAttributes([QgsField("field1", QVariant.Double)])
provider.addAttributes([QgsField("field2", QVariant.Double)])
provider.addAttributes([QgsField("field3", QVariant.Int)])
provider.addAttributes([QgsField("field4", QVariant.Int)])
provider.addAttributes([QgsField("field5", QVariant.Int)])
provider.addAttributes([QgsField("field6", QVariant.Double)])
new_layer.updateFields()

new_layer.startEditing()

for feat in new_layer.getFeatures():
    for i in new_list:
        feat['field1'] = i[0]
        feat['field2'] = i[1]
        feat['field3'] = i[2]
        feat['field4'] = i[3]
        feat['field5'] = i[4]
        feat['field6'] = i[5]
        new_layer.updateFeature(feat)
 
new_layer.commitChanges()

for field in new_layer.fields():
    print(field)
    print(field.name())
    print(field.type())

When I run this code, I see no errors but also no outputs. I was expecting the last for loop will return some properties of the new layer that I tried to create.

7
  • QgsVectorLayer.updateFeature() returns a boolean success indicator, best check that. I guess that you meant to use feature there, not feat? Mar 16, 2023 at 17:04
  • Thank you for your answer. Yes there is a typo there it should be feature not feat. But I couldn't understand what you meant by checking the QgsVectorLayer.updateFeature() part. Mar 16, 2023 at 19:00
  • Where do you use new_list? What is region1? Mar 16, 2023 at 19:39
  • Sorry, I changed the code with generic terms before posting here and forgot to change that line. new_list is `region1, I edited the post again. Mar 16, 2023 at 19:54
  • feature_updated = new_layer.updateFeature(feat) if feature_updated: # success else: # error with your logic Mar 16, 2023 at 19:58

1 Answer 1

7

You can use the "Extract by expression" tool to extract matching features from an input layer.

input_file = r"C:/path/input.shp"
output_file = r"C:/path/output.shp"
filter = ' "intensity" > 4 ' # Edit criteria

output_file_path = processing.run("native:extractbyexpression",
                                 {'INPUT':input_file
                                  'EXPRESSION':filter,
                                  'OUTPUT':output_file})["OUTPUT"]

# Uncomment the lines below if you need to add the new layer to the project
# new_layer = QgsVectorLayer(output_file_path, "LAYER_NAME", "ogr")
# QgsProject.instance().addMapLayer(new_layer)
2
  • runAndLoadResults() can also be useful ^_^
    – Taras
    Mar 18, 2023 at 7:44
  • @Taras You are right. But I thought the OP could use it as an intermediate process. Mar 18, 2023 at 21:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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