Just to add another method, you can set up a Project macro which when loaded:
- Automatically joins your shapefile to your csv
- Updates the
IP1
and IP2
fields
- Removes the joined fields leaving only the shapefile's fields (i.e. no dulplicates)
First, create a project if you haven't already done so and then go to the toolbar:
Project > Project Properties... > Macros
Then use the following code in the def openProject():
function and enter the names of your layers and the fields you want joined. I used "Example" and "spreadsheet" for my shapefile and csv file respectively with the field ID
:
from PyQt4.QtCore import *
import qgis
from qgis.core import QgsMapLayerRegistry, QgsVectorJoinInfo
for layer in QgsMapLayerRegistry.instance().mapLayers().values():
# Change to your shapefile name
if layer.name() == "Example":
qgis.utils.iface.setActiveLayer(layer)
shp = qgis.utils.iface.activeLayer()
for layer in QgsMapLayerRegistry.instance().mapLayers().values():
# Change to your csv name
if layer.name() == "spreadsheet":
qgis.utils.iface.setActiveLayer(layer)
csv = qgis.utils.iface.activeLayer()
# Set up join parameters
shpField='ID'
csvField='ID'
joinObject = QgsVectorJoinInfo()
joinObject.joinLayerId = csv.id()
joinObject.joinFieldName = csvField
joinObject.targetFieldName = shpField
shp.addJoin(joinObject)
# Define fields to update and joined fields to copy values from
ip1 = shp.fieldNameIndex('IP1')
ip1_join = shp.fieldNameIndex('spreadsheet_IP1')
ip2 = shp.fieldNameIndex('IP2')
ip2_join = shp.fieldNameIndex('spreadsheet_IP2')
shp.startEditing()
for feat in shp.getFeatures():
shp.changeAttributeValue(feat.id(), ip1, feat.attributes()[ip1_join])
shp.changeAttributeValue(feat.id(), ip2, feat.attributes()[ip2_join])
shp.commitChanges()
# Remove join
shp.removeJoin(csv.id())
Make sure that the layers are not joined, save the project and enable macros by going to the toolbar:
Settings > General > Enable macros
Now when you close the project and edit the csv file, the next time you load the project, the fields should automatically be updated: