1

I pretty often get lots of vector files with different column namings. I need to produce a defined vector data file with certain columns. Is it possible to build a model that allows to make a mapping? I hope my example is explaining my question:

I got a file with these two columns "City" and "Road". I need to get an output file with my two standard column names "Town" and "Street" these two new columns should contain the information of the original columns. Of course it would also work just to rename the input columns.

Input columns: "City", "Road" Output columns: "Town", "Street"

1

You could use a script which renames fields by entering the old name and a new name. You could run this from a model or independently:

Script interface


Here is the script which you can add from the Processing Toolbox:

from qgis.PyQt.QtCore import QCoreApplication, QVariant
from qgis.processing import alg
from qgis.core import edit

@alg(name='Example', label=alg.tr('Rename fields'), group='Example', group_label=alg.tr('Example'))
@alg.input(type=alg.SOURCE, name='INPUT', label='Input')
@alg.input(type=str, name="OLD_NAME", label="Old name", default='City')
@alg.input(type=str, name="NEW_NAME", label="New name", default='Town')
@alg.output(type=str, name="OUTPUT", label="Output")
def testAlg(instance, parameters, context, feedback, inputs):
    """
    Test script to change field names.
    """
    old_name = instance.parameterAsString(parameters, 'OLD_NAME', context)
    new_name = instance.parameterAsString(parameters, 'NEW_NAME', context)

    layer = instance.parameterAsVectorLayer(parameters, 'INPUT', context)
    for field in layer.fields():
        if field.name() == old_name:
            with edit(layer):
                idx = layer.fields().indexFromName(field.name())
                layer.renameAttribute(idx, new_name)

    return {}
  • This would work if I would know all the column names. But unfortunately I get new column names with each new shape file. I have a fix structure for the result table and need to define/map the incoming new vector files. – Pimpel Aug 21 at 13:44
1

I think you are looking for the

Refactor fields

This algorithm allows editing the structure of the attributes table of a vector layer. Fields can be modified in their type and name, using a fields mapping. The original layer is not modified. A new layer is generated, which contains a modified attribute table, according to the provided fields mapping.

from the processing tollbox.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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