Index de l'article

Joins

Join a CSV

import os
import shutil
 
myPath = r'C:\\Users\\georg\\Downloads\\'
 
project = QgsProject.instance()
project.removeAllMapLayers()
project.clear()
iface.mapCanvas().refresh()
 
crs = QgsCoordinateReferenceSystem.fromEpsgId(4326)
project.setCrs(crs)
project.setEllipsoid('EPSG:4326')
 
countries = QgsVectorLayer(myPath + 'simple_countries/simple_countries.shp', 'Countries', 'ogr')
 
project.addMapLayer(countries)
myCountries = project.mapLayersByName('Countries')[0]
 
extent_countries = countries.extent()
iface.mapCanvas().setExtent(extent_countries)
iface.mapCanvas().refresh()
 
# IMPORT CSV
csv_path = 'file:///' + myPath + 'World Stats.csv?delimiter=;'
my_csv = QgsVectorLayer(csv_path, 'Countries', 'delimitedtext')
project.addMapLayer(my_csv)
 
# JOIN 
shpField='COUNTRY_HB'
csvField='Country'
 
myJoin = QgsVectorLayerJoinInfo()
myJoin.setJoinFieldName(csvField)
myJoin.setTargetFieldName(shpField)
myJoin.setJoinLayerId(my_csv.id())
myJoin.setUsingMemoryCache(True)
myJoin.setJoinLayer(my_csv)
myJoin.setJoinFieldNamesSubset(['Population (2024)'])
myJoin.setPrefix('')
 
countries.addJoin(myJoin)
countries.dataProvider().forceReload()