I have one input layer with the attibute values and i wanted to join the attribute table of the input layer to the another layer with unique values using python. gis.stackexchange.com/questions/89706/how-to-merge-shape-files-with-attributes-from-a-python-script-in-qgis This link gives the information about about how to merge the features and attributes manually. but i want to join the atttribute tables. How can i do that using python?
You can join your two layers in this way:
# Get input and target layers targetLyr = iface.mapCanvas().layers() # Second layer from the ToC inLyr = iface.mapCanvas().layers() # First layer from the ToC # Set properties for the join targetField='myTargetField' inField='myInputField' joinObject = QgsVectorJoinInfo() joinObject.joinLayerId = inLyr.id() joinObject.joinFieldName = inField joinObject.targetFieldName = targetField targetLyr.addJoin(joinObject) # You should get True as response
EDIT: If you don't have your layers loaded into QGIS, you can access them from a directory in this way:
targetLyr = QgsVectorLayer('/path/to/layer1.shp', 'Layer 1', 'ogr') # I assume you use Shapefiles inLyr = QgsVectorLayer('/path/to/layer2.shp', 'Layer 2', 'ogr') # First layer from the ToC
If you want to use a solution with
processing as in How to merge shape files with attributes from a python script in QGIS? (without in the solution of gcarillo):
1) The easiest solution is to is to run the wanted algorithm from the toolbox and look at the
/.../.qgis2/processing/processing.log file. The last lines gives the solution:
ALGORITHM|Mon Jul 27 2015 16:29:33|processing.runalg("qgis:joinattributesbylocation","/Users/Shared/test.shp","/Users/Shared//test2.shp","['intersects', 'contains', 'equals', 'overlaps', 'within']",0,"sum,mean,min,max,median",1,None)
2) For the explanation, look at Using processing algorithms from the console:
import processing processing.alglist("join") Join attributes by location-------------------------->qgis:joinattributesbylocation Join attributes table-------------------------------->qgis:joinattributestable
and for the parameters:
processing.alghelp("qgis:joinattributesbylocation") .... processing.alghelp("qgis:joinattributestable") ....
With an example and comments in Overlay Analysis in QGIS (or Preferably Python)