Updating rows with an UpdateCursor

If you need to edit or delete rows from a table or feature class, you can use UpdateCursor. As is the case with InsertCursor, the contents of UpdateCursor can be limited through the use of a where clause.

Getting ready

The UpdateCursor() function can be used to either update or delete rows in a table or feature class. The returned cursor places a lock on the data, which will automatically be released if used inside a Python with statement. An UpdateCursor object is returned from a call to this method.

The UpdateCursor object places a lock on the data while it's being edited or deleted. If the cursor is used inside a Python with statement, the lock will automatically be freed after the data has been processed. This hasn't always been the case. Previous versions of cursors were required to be manually released using the Python del statement. Once an instance of UpdateCursor has been obtained, you can then call the updateCursor() method to update records in tables or feature classes and the deleteRow() method to delete a row.

In this recipe, you're going to write a script that updates each feature in the FireIncidents feature class by assigning a value of poor, fair, good, or excellent to a new field that is more descriptive of the confidence values using an UpdateCursor. Prior to updating the records, your script will add a new field to the FireIncidents feature class.

How to do it…

Follow these steps to create an UpdateCursor object that will be used to edit rows in a feature class:

  1. Open IDLE and create a new script.
  2. Save the script to c:ArcpyBookCh9UpdateWildfires.py.
  3. Import the arcpy and os modules:
    import arcpy,os
  4. Set the workspace:
    arcpy.env.workspace = "C:/ArcpyBook/Ch9/WildfireData/WildlandFires.mdb"
  5. Start a try block:
    try:
  6. Add a new field called CONFID_RATING to the FireIncidents feature class. Make sure to indent inside the try statement:
    arcpy.AddField_management("FireIncidents","CONFID_RATING","TEXT","10")
    print "CONFID_RATING field added to FireIncidents"
  7. Create a new instance of UpdateCursor inside a with block:
    with arcpy.da.UpdateCursor("FireIncidents",("CONFIDENCEVALUE","CONFID_RATING")) as cursor:
  8. Create a counter variable that will be used to print the progress of the script. Make sure you indent this line of code and all the lines of code to follow inside the with block:
    cntr = 1
  9. Loop through each of the rows in the FireIncidents fire class. Update the CONFID_RATING field according to the following guidelines:
    • Confidence value 0 to 40 = POOR
    • Confidence value 41 to 60 = FAIR
    • Confidence value 61 to 85 = GOOD
    • Confidence value 86 to 100 = EXCELLENT
      for row in cursor:
            # update the confid_rating field
            if row[0] <= 40:
              row[1] = 'POOR'
              cursor.updateRow(row)
            elif row[0] > 40 and row[0] <= 60:
              row[1] = 'FAIR'
              cursor.updateRow(row)
            elif row[0] > 60 and row[0] <= 85:
              row[1] = 'GOOD'
              cursor.updateRow(row)
            else:
              row[1] = 'EXCELLENT'
              cursor.updateRow(row)
      print "Record number " + str(cntr) + " updated"
      cntr = cntr + 1
  10. Add the except block to print any errors that may occur:
    except Exception as e:
      print e.message
  11. The entire script should appear as follows:
    import arcpy, os
    
    arcpy.env.workspace = "C:/ArcpyBook/Ch9/WildfireData/WildlandFires.mdb"
    try:
      #create a new field to hold the values
      arcpy.AddField_management("FireIncidents","CONFID_RATING","TEXT","10")
      print "CONFID_RATING field added to FireIncidents"
      with arcpy.da.UpdateCursor("FireIncidents",("CONFIDENCEVALUE","CONFID_RATING")) as cursor:
        cntr = 1
        for row in cursor:
          # update the confid_rating field
          if row[0] <= 40:
            row[1] = 'POOR'
          elif row[0] > 40 and row[0] <= 60:
            row[1] = 'FAIR'
          elif row[0] > 60 and row[0] <= 85:
            row[1] = 'GOOD'
          else:
            row[1] = 'EXCELLENT'
          cursor.updateRow(row)			
    print "Record number " + str(cntr) + " updated"
          cntr = cntr + 1
    except Exception as e:
      print e.message
  12. Save and run the script. You should see messages being written to the output window as the script runs:
    Record number 406 updated
    Record number 407 updated
    Record number 408 updated
    Record number 409 updated
    Record number 410 updated
    
  13. Open ArcMap and add the FireIncidents feature class. Open the attribute table and you should see that a new CONFID_RATING field has been added and populated by UpdateCursor:
    How to do it…

    Note

    When you insert, update, or delete data in cursors, the changes are permanent and can't be undone if you're working outside an edit session. However, with the new edit session functionality provided by ArcGIS 10.1, you can now make these changes inside an edit session to avoid these problems. We'll cover edit sessions soon.

How it works…

In this case, we've used UpdateCursor to update each of the features in a feature class. We first used the Add Field tool to add a new field called CONFID_RATING, which will hold new values that we assign based on values found in another field. The groups are poor, fair, good, and excellent, and are based on numeric values found in the CONFIDENCEVALUE field. We then created a new instance of UpdateCursor based on the FireIncidents feature class, and returned the two fields mentioned previously. The script then loops through each of the features and assigns a value of poor, fair, good, or excellent to the CONFID_RATING field (row[1]), based on the numeric value found in CONFIDENCEVALUE. A Python if/elif/else structure is used to control the flow of the script based on the numeric value. The value for CONFID_RATING is then committed to the feature class by passing in the row variable into the updateRow() method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.77.36