I would like to copy and paste the value from another feature sharing the same id in QGIS.

The feature to take the value from is always the only one with a value other than NULL per "id". Here what I am trying to achieve:

enter image description here

  • 1
    A nice question, but may I ask what have you tried by so far? What are your ideas? – Taras Dec 29 '20 at 9:25
  • 1
    I've thought of using an expression such as if("cat_f" is NULL, group_by:="id", "cat_f"="cat_f", NULL) But it does not make much sense yet... :) – Md01 Dec 29 '20 at 9:30
  • What is the logic QGIS should apply for choosing the feature to take the value from? Is there always only one feature with a value other than NULL per "id"? Please add the answer to your question's body. – bugmenot123 Dec 29 '20 at 11:12

You can use pyqgis:

lyr = iface.activeLayer() #Click layer in layer tree
fieldlist = ['id','cat_f']

data = [[f[fieldname] for fieldname in fieldlist] for f in lyr.getFeatures()]
#data is now: [[1, 'a'], [1, NULL], [2, 'b'], [2, NULL], [2, NULL], [3, NULL], [3, 'c']]

noNullData = [f for f in data if (f[1] is not None) and (f[1]!=NULL)]
#[[1, 'a'], [2, 'b'], [3, 'c']]

d = {id:data for id, data in noNullData}
#{1: 'a', 2: 'b', 3: 'c'}

fieldindex = lyr.fields().indexFromName(fieldlist[1])

with edit(lyr):
    for f in lyr.getFeatures():
        if f[fieldlist[0]] in d:
            f[fieldlist[1]] = d[f[fieldlist[0]]]

enter image description here


If you want to use QGIS expressions, use this expression here. In the screenshot below, I used it to create a new field, but you can as well use it to update an existing field:

"id"  || 
with_variable (
        array_agg ( 
            map ( "id", "cat_f") 
        @element is not NULL
    array_to_string (
        map_avals ( 
            array_get (
                array_foreach ( 
                    generate_series (
                        array_length (@mapunique)-1
                    array_get (
                ), "id"-1

enter image description here

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.