AnsweredAssumed Answered

ArcPy - Check a field type and execute depending on the type

Question asked by jsemanchik on Mar 13, 2015
Latest reply on Mar 20, 2015 by jsemanchik

Hello,

 

I'm not sure if this is the right place to send this so please correct me if I am wrong. 

 

I had a script that converted data from a clients site to a usable GIS format until they changed the output.  I've tried two different directions with no luck.  Due to how an earlier part of the script works, CSV to Table, and the nature of the data being converted; the 'total_length' field that's imported might end up being a string or an integer (TableToTable conversion will not work).  I need it to look at the field type and if it's already an integer then populate the 'length_val' field with the number.  If it's a string then strip it down to the number (typically the greater than, less than or tilde off the front) and populate the 'length_val' field. 

 

In other words:

If 'total_length' = STRING, then send only the number to 'length_val'

Otherwise, if 'total_length' = INTEGER, then calculate the field. 

 

I've been using update cursors to do a lot of the rest of the work, but that doesn't have to be the case.  Any assistance would be great. 

 

Thanks,

 

John

 

 

 

Row[3] = 'total_length'

Row[17] = 'length_val'

 

 

---First Attempt---

 

with arcpy.da.UpdateCursor(aoi_table_gdb,aoi_fields) as cursor:

    totlen = "total_length"  #<--- This was just an idea

    fields = arcpy.ListFields(aoi_table_gdb)

    for field in fields:

        if field.name = '"'+ totlen +'"' and field.type = String:

            for row in cursor:

                if row[3] == None:

                    row[17] = None

                elif row[3].find(str('~ ')) > -1:

                    row[17] = row[3].lstrip(str('~ '))

                elif row[3].find(str('> ')) > -1:

                    row[17] = row[3].lstrip(str('> '))

                elif row[3].find(str('< ')) > -1:

                    row[17] = row[3].lstrip(str('< '))

                else:

                    row[17] = row[3]

        else:

            for row in cursor:

                row[17] = row[3]

        cursor.updateRow(row)

 

 

 

 

---Second Attempt---

 

with arcpy.da.UpdateCursor(aoi_table_gdb,aoi_fields) as cursor:

    for row in cursor:

        #Length Value

        if row[3] == None:

            row[17] = None

            arcpy.AddWarning("A. Row: " + str(row[1]) + " - " + str(row[3]))

        elif row[3].isdigit():

            row[17] = row[3]

            arcpy.AddWarning("B. Row: " + str(row[1]) + " - " + str(row[3]))

        else:

            length = filter(unicode.isdigit, row[3])

            row[17] = length

            arcpy.AddWarning("C. Row: " + str(row[1]) + " - " + str(row[3]))

Outcomes