4

I have a mosaic data (over 500k rows) I want to run a UpdateCursor on to clean up a string field which roughly follows this pattern:

1432 Arequipa 92 PRINCIPAL SAT CAPTURE
2235 Pokhara 11 SECONDARY AERIAL PROGRAM

I want to end up with:

Arequipa 92
Pokhara 11

My attempt -

import arcpy

#get mosaic dataset layer
md = r"C:\...Mosaic"
mdl = arcpy.MakeMosaicLayer_management(md, "md_layer")

with arcpy.da.UpdateCursor(mdl,['FIELD']) as cursor:
    for row in cursor:
        try:
            fstrip = row[0][5:]
            rep1 = fstrip.replace("PRINCIPAL","")
            rep2 = rep1.replace("SAT","")
            rep3 = rep2.replace("CAPTURE","")
            rep4 = rep3.replace("PROGRAM","")
            rep5 = rep4.replace("SECONDARY","")
            rep6 = rep6.replace("AERIAL","")
            row[0] = rep6
            print(rep6)
            cursor.updateRow(row)
        except Exception:
            pass

This is obviously super inefficient - any tips to do a multiple replace while working around the immutability of the objects?

5

I dont think your code should be very inefficient, but you can shorten it.

If the field/string always have the words/numbers you want to extract in index 1 and 2, you can convert it to a list using split, extract index 1 and 2 with itemgetter and join back to a string with join:

import arcpy
from operator import itemgetter

mdl = "some_layer"

with arcpy.da.UpdateCursor(mdl,['FIELD']) as cursor:
    for row in cursor:
        row[0] = ' '.join(itemgetter(1,2)(row[0].split()))
        cursor.updateRow(row)

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.