I'm using PyQGIS 3.4, I am trying to add a new field and set the values equal to an existing field. The existing field are population totals but are in string format, I want to convert these to integers or real numbers.

I can add the new field however the problem is adding values to the field.

I am getting the following error.

exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "<string>", line 13, in <module>
TypeError: QgsExpression.prepare(): argument 1 has unexpected type 'int'


from qgis.core import *

from PyQt5.QtCore import *

output_layer = iface.activeLayer()

provider = output_layer.dataProvider()

provider.addAttributes([QgsField('new_pop', QVariant.Int)])



fieldIndex = output_layer.fields().indexFromName( 'new_pop' )

e = QgsExpression( 'toInt("exist_pop")' )

e.prepare(output_layer.fields().indexFromName( 'new_pop' ))


1 Answer 1


Thanks for your help, I decided to use a different strategy. Instead I created a .csvt file to accompany my csv file so that when I imported the csv the field was imported as a "integer".

opened notepad, saved the following as .csvt and saved in same location using same filename as my csv file.


PyQGIS code:


Your Answer

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

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