TransWikia.com

Copy and paste value from a feature sharing the same id

Geographic Information Systems Asked by Md01 on January 20, 2021

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

2 Answers

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])
#1

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

enter image description here

Correct answer by BERA on January 20, 2021

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 (
    'mapunique',
    array_filter(
        array_agg ( 
            map ( "id", "cat_f") 
        ),
        @element is not NULL
    ),
    array_to_string (
        map_avals ( 
            array_get (
                array_foreach ( 
                    generate_series (
                        0,  
                        array_length (@mapunique)-1
                    ),
                    array_get (
                        @mapunique, 
                        @element
                    )
                ), "id"-1
            )
        )
    )
)

enter image description here

Answered by babel on January 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP