Select to view content in your preferred language

Help with inconsistent indexing in a field.

58
1
3 hours ago
Labels (1)
gmaurer1123
New Contributor

Hello All, 

I am new to Python and struggling. Please see the screenshot below.  I have a text column (i.e. DUE_TIME) in a given shapefile that I need to split into a new field (i.e. VERSION). The problem I am having is that the original field (i.e. DUE_TIME) may have 1 OR 2 index positions at any given point feature. Some data points may have month/day/year, while others have month/day/year #. So, when I run the script below to try and "split" off the values at index position 1, I get an error stating "Index is out of range" even though some of the rows DO have a value in that index position. In this case, the VERSION field is created, but all rows in that field are blank.

 

Alternatively, I have tried changing the index value in the script to [-1], and while this does split off the # value where it exists, it simply splits off the month/day/year portion where the # does not exist (as seen in the screenshot). I also thought about adding a "0" after month/day year where the # value does not exist, but I am not sure how to write this. 

 

My goal is to have the DUE_TIME field only contain month/day/year and have the VERSION field only contain # or a 0, if # was not originally present in the DUE_TIME field. I hope my explanation makes sense. Any help will be greatly appreciated. 

 

import arcpy

fc = r"path\DP_Test_SHP"
arcpy.AddField_management("DP_Test_SHP", "VERSION", "TEXT")
with arcpy.da.UpdateCursor("DP_Test_SHP", ["DUE_TIME", "VERSION"]) as cursor:
for row in cursor:
row[1] = row[0].split(" ")[-1]
row=[i.strip() if i is not None else None for i in row]
cursor.updateRow(row)

gmaurer1123_0-1721318540970.png

 

 

0 Kudos
1 Reply
gmaurer1123
New Contributor

UPDATE: I was able to get it to work....

 

import arcpy

# Define the shapefile path
shapefile_path = r""

# Add a new field called "VERSION" to the shapefile
arcpy.AddField_management(shapefile_path, "VERSION", "TEXT")

# Update the "VERSION" field based on the "DUE_TIME" field
with arcpy.da.UpdateCursor(shapefile_path, ["DUE_TIME", "VERSION"]) as cursor:
for row in cursor:
# Split the "DUE_TIME" value by space
due_time_parts = row[0].split(" ")

# Check if the value at index 1 exists
if len(due_time_parts) > 1:
# If it exists, set the "VERSION" field to the value at index 1
row[1] = due_time_parts[1]
else:
# If it does not exist, set the "VERSION" field to "0"
row[1] = "0"

# Update the row
cursor.updateRow(row)

0 Kudos