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

This solution is so simple and easy to follow. After hours of looking through confusing threads. Thank you!
– Erich Purpur Nov 20 '18 at 16:13Say I wanted to add 1 to Patient_Data_PatientCount feature['Patient_Data_PatientCount'] is my expression to calculate this, but how? feature['Patient_Data_PatientCount + 1'] doesn't work. I feel like I can't even experiment with it since I can't find a usable (for my small brain) resource as an example – Erich Purpur Nov 20 '18 at 16:40
feature['Patient_Data_PatientCount']basically means that you are calling the value of the feature inside the field 'Patient_Data_PatientCount'. Notice that the field name is inside quotes. So if you want add 1 to this, you could usefeature['Patient_Data_PatientCount'] + 1. This could output an error though if the value is a string so it may be safer to use something likeint(feature['Patient_Data_PatientCount']) + 1to ensure the value is converted to integer before doing any arithmetic. Can't test this at the moment but hopefully it will help. – Joseph Nov 21 '18 at 10:45