2

I am new to working in QGIS-python environment, and I am trying to create a QGIS-plugin, where i want to create a new attributetable-column on a vector-layer based on some choices done by a user. A reclassifier so to say

So using GeoPandas, I would have collected the translation information in a dictionary with old information on left side, and the new information on the right. like

dictionary = {
        'old_data1' : 'new_data1',
        'old_data2' : 'new_data2',
        'old_data3' : 'new_data3',
    }

and then used geopandas .map() to create a new column based on this dictionary:

vectorlayer = gpd.read_file('vectorlayer.shp')
vectorlayer['new_class'] = vectorlayer['old_class'].map(dictionary)

Which would then create a new column with translated values.

Is there any similar function in the PyQGIS toolbox to use for this maneuver?

1 Answer 1

3

I dont know of a one-line solution like in pandas.

But you can try:

dictionary = {
        'old_data1' : 'new_data1',
        'old_data2' : 'new_data2',
        'old_data3' : 'new_data3'}

layer = iface.activeLayer()
newfieldindex = layer.fields().indexFromName('newfield') #The field needs to be created in advance
attrmap = {} #dictionary of feature id: {field index: new value}
for f in layer.getFeatures():
    if f['asdf'] in dictionary:
        attrmap[f.id()] = {newfieldindex:dictionary[f['asdf']]}

layer.dataProvider().changeAttributeValues(attrmap)

enter image description here

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.