4

I have ~200 shapefiles with data in neighborhoods by census blocks across the city. I want to join each of these shapefiles back to the main census block file so that a count column in each of the neighborhood shapefiles gets joined back to the original city census blocks shapefile. I thought I could do this in a batch process using the "join attributes table" function but it seems like this batch process will create 200 joined files, instead of just appending each joins onto the city shapefile table. Does anyone know how I can do this in QGIS? I am using QGIS 2.14.3

  • 1
    If this was my job, I would load all these shapefiles into PostGIS, as cumbersome as it sounds, into 1 table of 'neighborhoods', with proper attribution... then simply use SQL spatial to do the intersect and summary. Then you have 1 table with all the information you need... how did you end up with 200 shapefiles? Perhaps that requires more explanation? But I think either way you're going to have to merge them into 1 before you do the work. – DPSSpatial Aug 10 '16 at 1:30
  • Thank you, this is a good idea. I'll give it a try in PostGIS. – Lee R. Aug 10 '16 at 2:37
4

I would also recommend using PostGIS as mentioned by DPSSpatial but in QGIS, you could use a bit of python to loop through all your layers and perform a joins operation.

It uses a common field to join the main layer to each individual layer in the group. It only joins a field called "Count" from each individual layer. Edit the code to fit your layer/group/field names and paste into the Python Console:

# Define layer tree root and group
root = QgsProject.instance().layerTreeRoot()
layer_group = root.findGroup('Layer group')

# Define main layer and common fields from main layer and layers stored in group
main_layer = QgsMapLayerRegistry.instance().mapLayersByName('main_layer_name')[0]
main_layer_field = 'Field'
childField = 'Field'

# Iterate through each layer in group and join to main layer using defined fields
for layer in layer_group.children():
    joinObject = QgsVectorJoinInfo()
    joinObject.joinLayerId = layer.layerId()
    joinObject.joinFieldName = childField
    joinObject.targetFieldName = main_layer_field
    joinObject.setJoinFieldNamesSubset(['Count'])
    joinObject.memoryCache = True
    main_layer.addJoin(joinObject)

Your main layer should contain the "Count" field from the individual layers.

  • 1
    Thanks @Joseph - this worked. I made a change to line 13 so that the assignment is for the layer being iterated over. I will still need to try this over the 200 shps and may still setup this in PostGIS as DPSSpatial suggested. – Lee R. Aug 10 '16 at 19:53
  • @LeeR. - Most welcome, glad it was helpful and thanks for the edit :) – Joseph Aug 11 '16 at 8:29

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.