2

I'm having a little trouble using the merge command in QGIS. All the files have a range of different attributes, with some attribute headers in common. Some of these have different data format types for the common column, so when I try to merge them I get an error message.

I'm happy to delete all columns other one I've batch inserted, but how can I batch delete all columns other than one? I know I can use the Drop Fields Tool (/Delete Columns) but I'd have to individually select each column I want to delete in each of the layers.

0

2 Answers 2

4

If the field that you want to remain on every file has the same name, this will help:

import glob
from qgis.core import *

filter_ = "c:/_path_/*.shp" # or any file type supported by QgsVectorLayer    
field_name_to_remain = "field_name"

for file in glob.glob(filter_):
    layer = QgsVectorLayer(file, 'temp', 'ogr') # load file
    dpr = layer.dataProvider() # get dataprovider
    fields = dpr.fields() # get fields - QgsFields object

    field_index_list = []
    for f in fields:
        if f.name() != field_name_to_remain : 
            i = dpr.fieldNameIndex(f.name()) # get field index number
            field_index_list.append(i) # add to delete list

    dpr.deleteAttributes(field_index_list) # delete other fields
    layer.updateFields()

    del layer # from memory

NOTE: Before running the code, back up all files in your folder. Because the code change all original files in that folder.

2
  • Thanks Kadir Sahbaz. I'm a little new at scripting - is the above python? Where would I execute this from?
    – Joules
    Commented Apr 12, 2018 at 13:41
  • 1
    Before running the code, back up all files in your folder. Because the code change all original files in that folder. Open Python Console (Plugins > Python Console). Click 'Show Editor' button on top of the console window. Paste that code into the editor. And replace '_path_' string with your folder name and 'field_name' with field name to remain in the code (don't touch '/*.shp' part). And run script by "Run script" button (Play button). Commented Apr 12, 2018 at 14:05
0

The refactor tool should work for you

3
  • 1
    Do you mean Refactor Fields? This would mean selecting a number of columns on each of the (hundreds) of layers that need changing. I was hoping for something a little quicker.
    – Joules
    Commented Apr 12, 2018 at 10:42
  • I did, sorry my autocorrect must have changed it. If you do refactor in the model processor and use the formula to enter in only the fields you need, you won't have to load them all. Then you could use an iterator to repeate the process. Commented Apr 13, 2018 at 3:22
  • The comment should be an edit to the answer.
    – nmtoken
    Commented Apr 13, 2018 at 3:43

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.