Field Calculator PyQGIS – Struggling to Use Effectively

pyqgispyqgis-3qgisqgis-3

I'm using QGIS 3.4 (Madeira) and I am struggling to use python to calculate attributes of a new field in the attribute table.

I have already joined a csv and a shapefile. I use the code below to create a new column in the attribute table called 'PatCNT' with type as 'Int'

join_layer = QgsVectorLayer('/Users/ep9k/Desktop/SandraMonson/cb_2017_us_zcta510_500k/cb_2017_us_zcta510_500k.shp', 'US Zip Codes', 'ogr')

caps = join_layer.dataProvider().capabilities()
if caps & QgsVectorDataProvider.AddAttributes:
    join_layer.dataProvider().addAttributes([QgsField('PatCNT', QVariant.Double)])

Now, I have another column in my attribute table called Patient_Data_PatientCount (which is what I joined from the csv file).
I want to copy that column as an integer. When imported from a csv, it's type is 'String'

I've made some attempts based on other Stack Overflow threads like:

Is it possible to programmatically add calculated fields?

How to use QGIS field calculator in python?

Cannot calculate new values for an empty attribute using existing attributes in QGIS with python
However these are all for QGIS 2.18 and there are some differences (pendingFields doesn't exist anymore)

I've also been looking at the documentation and in the PyQGIS developers cookbook with no success

https://qgis.org/pyqgis/master/core/Expression/QgsExpression.html

https://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/vector.html

Best Answer

If you want to add an integer field, you should replace:

QVariant.Double

with

QVariant.Int

If your field from the csv is already joined to your shapefile, you could try using:

with edit(join_layer):
    for feature in join_layer.getFeatures():
        feature.setAttribute(feature.fieldNameIndex('PatCNT'), feature['Patient_Data_PatientCount'])
        join_layer.updateFeature(feature)