AnsweredAssumed Answered

arcpy.MakeXYEventLayer Help

Question asked by rexmorgan72 on Feb 17, 2013
Latest reply on Apr 26, 2013 by rexmorgan
Good Day. I have a csv file with weather stations and precipitation amounts by month. I want my code to ask which months the user would like to plot, open the csv file, add the precip data, and then plot the appropriate data on a map using ArcGIS 10.1 and python 2.7.  The code I have so far is listed below.

# ------------------------------------------------------------------------------------ # GISClimateMapping.py # Modified and Updated by Rex Morgan; Original Max Min Precip Snow .py by Josh Barnwell # Description: Creates GIS maps for Temperatures, and Rain and Snow Amounts. # ------------------------------------------------------------------------------------ # A Work in progress code 2-17-2013 1020 AM # Removed print statements # User Input of Month, Day, and what Variable to be plotted # Not sure why the test9-1.py failed. I originally believed that to be due to the  #  non capitalization of the Lat and Long variable but that seems to not be the #  case, as I have capitalized the variable.  import time import csv import array from time import gmtime, strftime print strftime("%Y-%m-%d %H:%M:%S", gmtime())   print ' ' print '                     ARCGIS Climate Data Mapping Program' print ' '  fname = 'Z:\\Desktop\\COOP_rainfall2.csv'  # read the data file data_list = [] for line in open(fname):     # remove trailing newline char     line = line.rstrip()     # create a list     line_list = line.split(',')     data_list.append(line_list)   # create a months dictionary with month:index pairs mdict = {} for ix, item in enumerate(data_list[0]):      if ix > 8:         mdict[item] = ix   #Gathering input from user  month1=raw_input('Input the 3 letter ID of beginning month  ')#getting input data from user month2=raw_input('Input the 3 letter ID of ending month     ')#getting input data from user  #assigning beginning and ending month here  month_start = month1 month_end = month2  #Create a new list new_list = [] outgroup = file("Z:\\Desktop\\test.csv", 'w') #this file is initially in the wrong format. for item in data_list[1:]:      station = item[0]     lat = item[2] #Remembe to change this value if altering the structure of the input file Z:\\Desktop\\COOP_rainfall2.csv     long = item[3]     start = mdict[month_start]     end = mdict[month_end]+1     plist = [float(x) for x in item[start : end] if x] #having trouble with blanks         if plist:       mysum = sum(plist)     new_list.append([station, lat, long, mysum])   for item in new_list:      outgroup.write(str(item)) #this does produce a file with the info contained therein but not quite what I want     #new_file.write("%s\n" % item) f= open("Z:\\Desktop\\test2.csv", 'w') # This file needs to be different than the one in line 35 of code.   for row in new_list:     f.write(','.join(map(str,row))+'\n')    new_list.insert(0,['Station', 'Lat', 'Long', 'mysum']) # this ran without errors and did add the values to the beginning of list ## this line added at 2-17-2013 933 AM  f= open("Z:\\Desktop\\test3.csv", 'w') for row in new_list:     f.write(','.join(map(str,row))+'\n')   print '     This is the end of the test6.py file.     Now for the rest of it. '  Rex = 'Z:\\Desktop\\test3.csv'  ### Hack this part back in Precip=[] #creating an array named Precip inp = open (Rex,"r") # Rex defined in line 22 of code for line in inp.readlines():  line.split(',')  Precip.append(line) file.close(inp) ##### The part above hacked back in  print ' ' print 'This will take about 2 to 5 minutes...'  month = month1 + ' through ' + month2 months = month usermonth = "[" + months + "]"  # Import arcpy module import arcpy import arcpy.mapping  # Check out any necessary licenses arcpy.CheckOutExtension("spatial")  import sys, string, os  # Directories tempdir = 'CSV\\' directory = 'N:\\climate\\ClimateSheets\\' + str(tempdir) TopoToR = 'R:\\ArcGIS\\default.gdb\\TopoToR'   # Local variables:  GGW_Counties = "R:\\fxc\\Western Region FXC Packet\\GGW.shp" Var_layer = months # variable assigned in line 40 of code Var_shp = str(directory) + 'Var.shp' Var_new = str(directory) + 'Varnew.shp' Var_img = str(directory) + 'Var.img' Var100_img = str(directory) + 'Var100.img' Vari100 = str(directory) + 'Vari100' Varcontour_shp = str(directory) + 'Varcontour.shp' Output_stream_polyline_features = "" Output_remaining_sink_point_features = "" Output_diagnostic_file = "" Output_parameter_file = "" TopoToRasterExtent= "-108.891024 46.540403 -104.041596 49.000027" spRef = r"Coordinate Systems\Geographic Coordinate Systems\World\WGS 1984.prj" print 'Made it through Local variables'   import arcview import sys, string, os, arcgisscripting gp = arcgisscripting.create(10.1) gp.SetProduct("ArcView") # or ArcEditor or ArcInfo gp.overwriteoutput = 1 #arcpy.overwriteOutput = True print 'Made it through import arcview'  ### Getting error in the arcpy.MakeXYEventLayer_management ---- "Long" does not extist "Lat" does not exist # Process: Make XY Event Layer arcpy.MakeXYEventLayer_management(Rex, "Long", "Lat", Var_layer, spRef, "") #Rex is defined in line 90 of code as Z:\\Desktop\\test3.csv print 'Make XY Event Layer Done'   # Process: Copy Features arcpy.CopyFeatures_management(Var_layer, Var_shp, "", "0", "0", "0") print 'Copy Features Done'   # Process: Topo to Raster from arcpy import env env.extent = "-108.891024 46.540403 -104.041596 49.000027"  from arcpy.sa import * outTTR = TopoToRaster([TopoPointElevation([[Var_shp, Var_layer]])], "0.003", "", "20", "", "", "ENFORCE", "CONTOUR", "", "", "", "", "", "") outTTR.save(TopoToR) print 'Topo To Raster Done'   # Process: Clip arcpy.Clip_management(TopoToR, "-108.891024 46.540403 -104.041596 49.000027", Var_img, GGW_Counties, "", "ClippingGeometry") print 'Clip Done'   # Process: Define Projection for Shapefile in order to plot record values correctly ggw_shp = 'R:\\fxc\\Western Region FXC Packet\\GGW.shp' dsc = arcpy.Describe(ggw_shp) coord_sys = dsc.SpatialReference arcpy.DefineProjection_management(Var_shp, coord_sys) print 'Define Projection Done' print strftime("%Y-%m-%d %H:%M:%S", gmtime())  print 'Exporting Map' from datetime import date now = date.today().isoformat() mxd1 = arcpy.mapping.MapDocument(r"R:\EventData\CoopPrecip1024.mxd") mxd3 = arcpy.mapping.MapDocument(r"R:\EventData\CoopPrecip13.mxd")      #newtitle = arcpy.mapping.ListLayoutElements(mxd3, "TEXT_ELEMENT", "title")[0]  if 'YTD' in months: #months defined in line 20   print 'if statement'   newtitle = arcpy.mapping.ListLayoutElements(mxd1, "TEXT_ELEMENT", "title")[0]   for lyr in arcpy.mapping.ListLayers(mxd1):    if lyr.name == "Var":      if lyr.supports("LABELCLASSES"):        lblClass = lyr.labelClasses[0] #this is the Default label class.        lblClass.expression = usermonth   newtitle.text = 'Annual COOP Precipitation Year to Date'   arcpy.mapping.ExportToPNG(mxd1, r'R:\\Maps\\' + months + str(now) + '.png', resolution=100) #months defined in line 20 else:   print 'else statement'   newtitle = arcpy.mapping.ListLayoutElements(mxd3, "TEXT_ELEMENT", "title")[0]   for lyr in arcpy.mapping.ListLayers(mxd3):    if lyr.name == "Var":      if lyr.supports("LABELCLASSES"):        lblClass = lyr.labelClasses[0] #this is the Default label class.        lblClass.expression = usermonth   newtitle.text = 'Monthly COOP Precipitation for ' + month # month defined in line 40   arcpy.mapping.ExportToPNG(mxd3, r'R:\\Maps\\' + months + str(now) + '.png', resolution=100) #months defined in line 20    print 'Map is Complete and located in R:\Maps'  print strftime("%Y-%m-%d %H:%M:%S", gmtime())


The problem I have is that I am getting an error in the MakeXYEventLayer. I will quote it below:

Traceback (most recent call last):
  File "\home\rex.morgan\Desktop\Temp\test9-3.py", line 151, in <module> arcpy.MakeXYEventLayer_management(Rex, "Long", "Lat", Var_layer, spRef, "")

File "C:\Program Files (x86)\ArcGIS\Desktop10.1\arcpy\arcpy\management.py" line 6322, in MakeXYEventLayer raise e

acrgisscripting.ExecuteError: Failed to execute. Parameters are not valid.
ERROR 000728: Field Long does not exist within table
ERROR 000728: Field Lat does not exist within table
Failed to execute (MakeXYEventlayer).


Any ideas would be greatly appreciated.

Outcomes