2

I have the code below. fc is a shapefile. I add a new field called "RANK". I want to populate the RANK column with values from Final_Rank list. Fortunately, they are of the same size. Field RANK has got 11 rows and Final_Rank has 11 values. The code below creates the field RANK and then adds 11 additional rows, below the existing 11 rows in the attribute table and inserts the values to RANK beginning notfrom the start but from the 11 additional rows. I want the code to add the values to the existing RANK field without adding any rows.

print Final_Rank

arcpy.AddField_management(fc, "RANK", "Double")

with arcpy.da.InsertCursor(fc, 'RANK') as cursor:
    for i in Final_Rank:
    cursor.insertRow(i)
3

You should be using UpdateCursor instead:

print Final_Rank

arcpy.AddField_management(fc, "RANK", "Double")
pointer = 0
with arcpy.da.UpdateCursor(fc, 'RANK') as cursor:
     for row in cursor:
         row[0] = Final_Rank[pointer]
         pointer += 1
         cursor.updateRow(row)
  • exactly what i needed. Can you explain a bit the pointer purpose? – Thanos Smar Mar 2 '17 at 14:24
  • pointer is a variable that indicates what position in the Rank_List is going to be copied to the row[0] attribute. So, once with opens the fc, and the for statement opens the first row in your fc, the pointer value is 0. So the line row[0]=Final_Rank[pointer] will assign the content of the list (Final_Rank) in the first position to the 'Rank' attribute (in that first line). Then pointer will be increased in one, and the changes will be updated. – Delonix R. Mar 2 '17 at 14:35
  • Cont... The next time in the for loop, row[0] will get the value of Final_Rank in the position 2 (that is what pointer is for, increments the position in the table to be read)... and so on... Enjoy coding... – Delonix R. Mar 2 '17 at 14:35
0

Insert Cursor is for adding new rows:

InsertCursor can be used to add new rows.

From what i understand you dont want new rows. You want to populate the new field RANK with the values in list Final_Rank. For this you should use the Update Cursor:

UpdateCursor establishes read-write access to records returned from a feature class or table.

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.