2

I am trying to add new field to my table based on two other existing fields. In the field Calculator it's quite simple:

My Goal

When I am trying to run as a Python code I got into trouble, Here's my code:

vLayer = iface.activeLayer()    
vLayer.dataProvider().addAttributes([QgsField('1m_Cases', QVariant.Int)])
vLayer.updateFields()
for f in vLayer.getFeatures(): 
        f.setAttribute(f.fieldNameIndex('1m_Cases'), f(['J_TotalCases'] *1000000)/ f['Pop'])
vLayer.commitChanges()    
0

2 Answers 2

2

you can change the code like below, which should work:

vLayer = iface.activeLayer()
vLayer.dataProvider().addAttributes([QgsField('1m_Cases', QVariant.Int)])
vLayer.updateFields()
vLayer.startEditing()
for f in vLayer.getFeatures():
    f['1m_Cases'] = f['J_TotalCases'] *1000000/ f['Pop']
    vLayer.updateFeature(f)
vLayer.commitChanges()   
4
  • Can you not mix the use of dataprovider and editing session? Either use only the dataprovider or the editing buffer. Thanks
    – etrimaille
    Apr 16, 2020 at 7:19
  • I tried to run the code but I got the error: TypeError: unsupported operand type(s) for *: 'QVariant' and 'int'??
    – user130952
    Apr 18, 2020 at 0:41
  • 1
    I've tried the code, but there was no error. The error indicates, that in the line with f['J_TotalCases'] *1000000/ f['Pop'] something goes wrong. May be you'll try: from PyQt5.QtCore import QVariant
    – eurojam
    Apr 18, 2020 at 4:57
  • Thanks it was a mistype on my end. It's working now
    – user130952
    Apr 19, 2020 at 20:11
2

Based on the answer from @eurojam but using only the editing buffer, like in QGIS GUI.

from qgis.core import edit

vLayer = iface.activeLayer()
with edit(vLayer)
    vLayer.addAttribute(QgsField('1m_Cases', QVariant.Int))
    for f in vLayer.getFeatures():
        f['1m_Cases'] = f['J_TotalCases'] *1000000/ f['Pop']
        vLayer.updateFeature(f)
1
  • Thanks for your quick help, will try it now...
    – user130952
    Apr 16, 2020 at 18:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.