Sunday 8 January 2017

Python to create new fields in many layers / QGIS


I have a number of line layers on which I need to perform the same task: add 4 columns with the start and end points of each line.


The expressions that I use to do this are:


$xat(0)
$xat(-1)
$yat(0)
$yat(-1)


However, I must create a new column and update it for every layer, but I am sure that it can be automated. Any ideas on how to perform the creation of 4 new columns on every layer in the layers panel in QGIS?



Answer



As mentioned in the comment, you could create a model from the Processing Toolbox but if you want to create a script, you could use the following which creates the start_lat field and updates it for each layer (comments are included which hopefully will help):


# Import required module to create field
from PyQt4.QtCore import QVariant

# For each layer in panel
for layer in QgsMapLayerRegistry.instance().mapLayers().values():
# Add a real field (which uses decimal)
layer.dataProvider().addAttributes( [ QgsField("start_lat", QVariant.Double) ] )

# Update attribute table with new field
layer.updateFields()
# Begin editing of layer and finish loop with saving edits
with edit(layer):
# Let `idx` = field with name "start_lat"
idx = layer.fieldNameIndex( "start_lat" )
# Define expression
e = QgsExpression( """ $x_at(0) """ )
e.prepare( layer.pendingFields() )
# For each feature in layer

for f in layer.getFeatures():
# Apply expression
f[idx] = e.evaluate(f)
# Update attribute table
layer.updateFeature(f)

You could then repeat the above by adapting it to create the other 3 fields or extend the loops and create all 4 fields at once.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...