I am trying to use Python for QGIS to add values to new fields in an attribute table based on existing fields and values in a lookup table.
Attribute table I wish to modify (with example rows):
farm | ref_1 | ref_2 | newField_1 | newField_2Macdonald | seeds | veg | | Fred | seeds | fruit | | Bob | seeds | fruit | | Lookup table:
ref_1 | ref_2 | lookup_1 | lookup_2seeds | fruit | 13 | 4seeds | veg | 10 | 3Assuming newFields 1 & 2 have been added to the attribute table, my code is as follows:
aLayer = qgis.utils.iface.activeLayer()provider = aLayer.dataProvider()lookup_table = np.loadtxt(r'filepath\myfile.csv',dtype=str,delimiter=',',skiprows=1)aLayer.startEditingfor feature in aLayer.getFeatures(): for i in lookup_table: if i[0] == feature['ref_1'] and i[1] == feature['ref_2']: provider.changeAttributeValues({feature.id() : {provider.fieldNameMap()['newField_1'] : i[2]}}) provider.changeAttributeValues({feature.id() : {provider.fieldNameMap()['newField_2'] : i[3]}}) aLayer.updateFeature(feature)aLayer.commitChanges()After running the code, the newFields 1 & 2 remain null.
Referring to this post I can get provider.changeAttributeValues() to work based off of fields within the same table; however, if I reference a lookup table it fails. Any help is appreciated!
أكثر...
Attribute table I wish to modify (with example rows):
farm | ref_1 | ref_2 | newField_1 | newField_2Macdonald | seeds | veg | | Fred | seeds | fruit | | Bob | seeds | fruit | | Lookup table:
ref_1 | ref_2 | lookup_1 | lookup_2seeds | fruit | 13 | 4seeds | veg | 10 | 3Assuming newFields 1 & 2 have been added to the attribute table, my code is as follows:
aLayer = qgis.utils.iface.activeLayer()provider = aLayer.dataProvider()lookup_table = np.loadtxt(r'filepath\myfile.csv',dtype=str,delimiter=',',skiprows=1)aLayer.startEditingfor feature in aLayer.getFeatures(): for i in lookup_table: if i[0] == feature['ref_1'] and i[1] == feature['ref_2']: provider.changeAttributeValues({feature.id() : {provider.fieldNameMap()['newField_1'] : i[2]}}) provider.changeAttributeValues({feature.id() : {provider.fieldNameMap()['newField_2'] : i[3]}}) aLayer.updateFeature(feature)aLayer.commitChanges()After running the code, the newFields 1 & 2 remain null.
Referring to this post I can get provider.changeAttributeValues() to work based off of fields within the same table; however, if I reference a lookup table it fails. Any help is appreciated!
أكثر...