I am trying to copy features from one layer to another. What I would like to do is for QGIS to ask me which field should each field copy to.

For example, layer A has 4 features that I am trying to copy to layer B. Now layer A has 5 fields A1, A2, and so on. Similarly, layer B has 5 fields but with different names B1, B2, and so on.

Is there a way I can assign field A3 to copy to B1 and A5 to copy to B2?


If layer B had A and B fields, you could add defaults values to B fields, for example field "B1" would be equal to "A3" and "B2" to "A5".

When copying the A features in B, fields A1,2,3.. would insert with no changement, and B fields would create default values from it. You would only have to delete A fields when finished.

| improve this answer | |
  • Thanks, I like your answer and know other ways around as well. But I am looking for a direct way to do it. – ar-siddiqui Sep 17 '19 at 21:47

Although you haven't tagged this question with pyqgis, you could achieve your goal by using the script below and pasting it into an editor in the python console and clicking run.

The field name mapping is set up in nested lists with the format:

[['Source field name', 'Target field name'], ['Source field name', 'Target field name']]

etc. and assigned to a variable. You can change the source and target field name in each internal list to suit your needs.

Then just make sure these two lines contain the actual names of your source and target layers.

layer_1 = project.mapLayersByName('Name of your source layer')[0]

layer_2 = project.mapLayersByName('Name of your target layer')[0]

The code will copy the selected features from layer_1, so make sure you have features selected before you run it. Alternatively, if you wish to copy all Layer_1 features, you can change this line:

L1_feats = [f for f in layer_1.selectedFeatures()]


L1_feats = [f for f in layer_1.getFeatures()]

Complete code:

project = QgsProject().instance()
# Set up field mapping in lists below e.g. ['Layer A field name', 'Layer B field name']
fld_map = [['A1', 'B3'],
            ['A2', 'B5'],
            ['A3', 'B1'],
            ['A4', 'B4'],
            ['A5', 'B2']]

layer_1 = project.mapLayersByName('Layer A')[0] # change 'Layer A' to the name of your source layer
L1_feats = [f for f in layer_1.selectedFeatures()]

layer_2 = project.mapLayersByName('Layer B')[0] # change 'Layer B' to the name of your target layer
pr_2 = layer_2.dataProvider()
for feat in L1_feats:
    atts = {}
    for item in fld_map:
        atts[layer_2.fields().lookupField(item[1])]= feat.attribute(layer_1.fields().lookupField(item[0]))
    L2_feat = QgsFeature()
    pr_2.changeAttributeValues({L2_feat.id(): atts})
| improve this answer | |

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.