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:
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It only takes a minute to sign up.
Sign up to join this communityI 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:
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)
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
)
)
)
)