0

Since I work a lot with routing and trip matrices I have a daily need for joining two layers by two attributes (origin and destination).

I have had AI to support me in writing a Processing Script for doing this and it looks good except for that it doesnt function ;-)

Feeding error message back to AI just send me in a loop of changes leading nowhere.

NB: I am aware this can be done in many other ways (SQL in Virtual layers, defining ONE custom join attribute etc. but that is not my interest!)

[enter image description here

enter image description here

Script and test data here: Test.zip

1

1 Answer 1

0

I'm afraid your generative AI has let you down here. This QGIS processing algorithm ("native:joinattributestable") joins tables by one matching field only, and expects a string as the processing parameters for FIELD and FIELD_2. Your script is trying to provide a list of fields which is why it is failing.

An alternative would be to use geopandas to carry out the processing, you can still execute it in QGIS. You may need to install geopandas via OsGeo shell, then you can run this in the QGIS python console.

import geopandas as gpd
import pandas as pd

# User inputs
layer_a_path = "path/to/file"
layer_b_path = "path/to/file"
output_path = "path/to/destination"
fields_a = ["field1","field2"]
fields_b = ["field1","field2"]

# Processing
layer_a = gpd.read_file(layer_a_path) # Open layer 1
layer_b = gpd.read_file(layer_b_path) # Open layer 2

output = pd.merge(layer_a, layer_b, left_on=fields_a, right_on=fields_b)
gpd.GeoDataFrame(output, geometry="geometry_x").to_file(output_path)

# If executing in the QGIS python console, include the following
iface.addVectorLayer(output_path, "Output", "ogr")

If you'd rather work from a GUI, you could adapt your PyQGIS script to provide a GUI which captures user inputs but executes the processing part of the below code within the processAlgorithm() function.

A cleaner alternative would be to use a Virtual Layer as you suggest in your question, although I understand you aren't keen on this idea.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.