0

I have a points shapefile with almost 1 million features. I would like to add three new attributes: y, x (coordinates) and an ID (integers from 1).

How can I perform this task in R or PyQGIS? Using QGIS field calculator makes the software crash because the shapefile is too heavy.

0

Here it is something I would do (I didn't test the code)

layer.startEditing()

# new field x
nfx = layer.dataProvider().addAttributes( [ QgsField("X", QVariant.String)] )
# new field y
nfx = layer.dataProvider().addAttributes( [ QgsField("Y", QVariant.String)] )
# new field ID
nfid = layer.dataProvider().addAttributes( [ QgsField("newID", QVariant.String)] )


layer.commitChanges()

indexX = layer.fieldNameIndex('X')
indexY = layer.fieldNameIndex('Y')
indexID = layer.fieldNameIndex('newID')
features = layer.getFeatures()

layer.startEditing()

ID = 1

for f in features:
   layer.changeAttributeValue(f.id(), indexX, str(f.geometry().asPoint.x()))
   layer.changeAttributeValue(f.id(), indexY, str(f.geometry().asPoint.y()))
   layer.changeAttributeValue(f.id(), indexID, str(ID))
   ID += 1

layer.commitChanges()
layer.updateFields()
QgsVectorFileWriter.writeAsVectorFormat(layer, "PathToSHape.shp", "utf-8", None, "ESRI Shapefile")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.