0

I have two layers where different columns exist. I want to copy a layer column into antoher layer column programatically. I have done the below code so far:

layerNameValueSet = "PLATFORM"
#columnNameSet where to value add
columnNameSet = "ZONEID"

#LayerName Where to copy column values
layerNameValueGet= "LOT" 
#Above layer's[layerNameValueGet] cloumn name from value will be get for copy in layerNameValueSet
columnNameGet = "ZONEID"

#Getting layer of specifc name
layerNameValueSetObj = QgsMapLayerRegistry.instance().mapLayersByName(layerNameValueSet)[0];
layerNameValueGetObj = QgsMapLayerRegistry.instance().mapLayersByName(layerNameValueGet)[0];

fieldIndexToSet = layerNameValueSetObj.fieldNameIndex(columnNameSet)
fieldIndexToGet = layerNameValueGetObj.fieldNameIndex(columnNameGet)

for getFeature in layerNameValueGetObj.getFeatures():

    #this logic is not correct /taking too much time hanging

for setFeature in layerNameValueSetObj.getFeatures():
    if(getFeature.id() == setFeature.id()):
        layerNameValueSetObj.startEditing()
        updateValue = getFeature[columnNameGet]
        layerNameValueSetObj.changeAttributeValue(setFeature.id(), fieldIndexToSet, updateValue)
        layerNameValueSetObj.commitChanges()
julsbreakdown
  • 1,496
  • 10
  • 21

2 Answers2

0

You could :
- instead of editing / commiting in a loop. Build a list or even a dic. And so you would just need to commit once.
- Why not use the join by attribut tool instead of reinventing the wheel: see helpfull script

this could also help : link1, link2

julsbreakdown
  • 1,496
  • 10
  • 21
0

Finally zip help me to do this Job. I run both loop simultaneously in one loop and here is the answer:

import itertools
#layerNameValueSet Where to copy column values
layerNameValueSet = "PLATFORM"
#columnNameSet where to value add
columnNameSet = "ZONEID"

#LayerName Where to copy column values
layerNameValueGet= "LOT" 
#Above layer's[layerNameValueGet] cloumn name from value will be get for copy in layerNameValueSet
columnNameGet = "ZONEID"

#Getting layer of specifc name
layerNameValueSetObj = QgsMapLayerRegistry.instance().mapLayersByName(layerNameValueSet)[0];
layerNameValueGetObj = QgsMapLayerRegistry.instance().mapLayersByName(layerNameValueGet)[0];

fieldIndexToSet = layerNameValueSetObj.fieldNameIndex(columnNameSet)
fieldIndexToGet = layerNameValueGetObj.fieldNameIndex(columnNameGet)

#running two loops simeltenously so that copy one value into antoher
for getFeature, setFeature in zip(layerNameValueGetObj.getFeatures(), layerNameValueSetObj.getFeatures()):
    layerNameValueSetObj.startEditing()
    updateValue = getFeature[columnNameGet]
    layerNameValueSetObj.changeAttributeValue(setFeature.id(), fieldIndexToSet, updateValue)
    layerNameValueSetObj.commitChanges()