2

I am brand new to Python and am having trouble with this objective in my Intro to Python for GIS assignment:

Independent step… Create two new fields in the attribute table named X and Y (or something handy). Populate that field with the X,Y location of the oilspill points themselves!

Note: The oilspills featureclass has many points already with set geometry but the coordinates are not given in the existing table.

I have successfully created the new columns called X and Y using the following code:

import arcpy

oilspills = 'S:\\Lab 2\\oilspills.shp'

arcpy.AddField_management(oilspills, "X", "DOUBLE", "", "", "13", "", "NON_NULLABLE", "NON_REQUIRED", "")
arcpy.AddField_management(oilspills, "Y", "DOUBLE", "", "", "13", "", "NON_NULLABLE", "NON_REQUIRED", "")

My issue now is that I can't figure out how to populate those new columns with the x and y coordinates for each point in the table. That said, I have managed to print out all the x and y coordinates for each point in the featureclass via the Python shell:

import arcpy

with arcpy.da.UpdateCursor('s:\\Lab 2\\oilspills.shp',['SHAPE@X','SHAPE@Y']) as cursor:
    for row in cursor:
        print row[0]
        print row[1]

But I'm not sure how to combine the first part of my code and the second so the new columns I've created get populated with those values. How can I do this?

1
  • Welcome to GIS SE! As a new user please take the new user tour to learn about our focused Q&A format.
    – Midavalo
    Apr 8, 2017 at 22:10

1 Answer 1

3

You're very close - you just need to add your new fields into your cursor and set the value for X to be the value from SHAPE@X

import arcpy

oilspills = 'S:\\Lab 2\\oilspills.shp'

arcpy.AddField_management(oilspills, "X", "DOUBLE", "", "", "13", "", "NON_NULLABLE", "NON_REQUIRED", "")
arcpy.AddField_management(oilspills, "Y", "DOUBLE", "", "", "13", "", "NON_NULLABLE", "NON_REQUIRED", "")

with arcpy.da.UpdateCursor(oilspills, ['SHAPE@X', 'SHAPE@Y', 'X', 'Y']) as cursor:
    for row in cursor:
        # Populate X from Shape X
        row[2] = row[0]
        # Populate Y from Shape Y
        row[3] = row[1]
        # Save changes
        cursor.updateRow(row)

To add a bit of explanation, your list of fields ['SHAPE@X', 'SHAPE@Y', 'X', 'Y'] are indexed in the row as 0, 1, 2, 3, so the SHAPE@X is index 0 and X is index 2. So row[2] = row[0] means you are populating the X field with the value from the SHAPE@X field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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