1

I'm trying to add to a shapefile a point that is a (x-y) distance away from another point (city). None of the cities in the shapefile have x-y coordinates in the attribute table; I've added them for the latter city alone. To obtain them with the searchCursor I'm using the following code:

import arcpy

featureclass = "C:\temp\CITIES.shp"
fields = ["CITY_FIPS","CITY_NAME","x","y"]

with arcpy.da.SearchCursor(featureclass,fields) as cursor:
    for row in cursor:
        if row[0] == "17800":
        print ('{1}'.format(row[1]))

Which yields the "IndexError: tuple index out of range" for the last line. Am I not referencing "CITY_NAME" with row[1]?

After resolving that, how could I go about adding a new city (point) to the shapefile (using insertCursor)?

  • index starts with 0 so: print ('{0}'.format(row[1])). You dont need to add x and y fields, instead use the shape tokens, for example "SHAPE@XY". Or are you saying that the x and y field are the relative postition of the new Point compared to the old one? – BERA Mar 27 at 6:24
  • I've tried using "SHAPE@XY" but without success, and I think that's because the shapefile does not have x-y coordinates included in the attribute table. I added x and y fields to the CITIES.shp attribute table, but I only calculated the values for the old city. I've been trying to find a way to use those to insert the new city (i.e. New City should be located at x+0.02 and y-0.03). – andm Mar 27 at 6:29
  • Hi @andm, for the sake of the site's posterity: don't ask more than one question per post. Here, for example, when you ask "After resolving that, how could I go about adding a new city (point) to the shapefile (using insertCursor)?", you're addressing a whole different matter. Such a thing should be in it's own question. – Paulo Raposo Mar 27 at 8:06
1

The error you are getting is because index starts with 0 and you are using 1 in the format row. Change to:

print ('{0}'.format(row[1]))

You can then use the insertCursor with the SHAPE@XY token, no need to add x and y fields:

import arcpy

fc = 'points'
x_move = 1000
y_move = 500
fields = ["CITY_FIPS","CITY_NAME","SHAPE@XY"]

template_point = list([i for i in arcpy.da.SearchCursor(fc,fields) if i[0]=="17800"][0])
#template Point is now: [u'17800', u'Whatever', (504076.8245000001, 6493719.2324)]

template_point[-1] = (template_point[-1][0]+x_move, template_point[-1][1]+y_move)

icur = arcpy.da.InsertCursor(fc, fields)
icur.insertRow(template_point)
del icur

enter image description here

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.