2

I have a shapefile with polygons and each polygon has an ID number that follows a pattern like this:

SMP_ID
1077-1-1
8-2-2
1281-1-3
304-2-1

In have created a new field and I need to populate it with a truncated version of these IDs, which would look like this:

SYS_ID
1077-1
8-2
1281-1
304-2

This is the code I've been fiddling with most recently, I feel like it's the closest...

def getSysID(SMP_ID):
 if SMP_ID is None:
  return None
 else:
  SysID = SMP_ID.split('-')[0] + '-' + SMP_ID.split('-')[1]
  return SysID

I also tried this method:

id_vals = !SMP_ID!.split("-")

SYS_ID = id_vals[0] + "-" + id_vals[1]

remainder = id_vals[2]

Something isn't working right, though! There are a few IDs from a different source that don't follow this pattern and are just a string of numbers without hyphens, I'm wondering if that could be a part of the problem?

I'm looking for a solution that will ignore the non-hyphenated IDs and nulls, and copy the truncated hyphenated IDs into a new field.

2

Using the built-in string method of 'find', you can identify whether there is a hyphen in the field and process accordingly. One reason you may have errors is that on non-hyphenated records, there is no item at index position 1 from the split.

def getSysID(SMP_ID):
   if SMP_ID.find("-") == -1 or SMP_ID is None: #might be able to leave off the or clause here
       return None
   else:
       SysID = SMP_ID.split('-')[0] + '-' + SMP_ID.split('-')[1]
       return SysID
  • When I tried it with the "or" clause, it gave an error, but once I omitted it, it worked like a charm! Thank you for the help! – Shaleby Feb 25 at 18:30
  • 1
    Might be a format error for or, I'll check and update later. Glad that worked! – smiller Feb 25 at 18:32
  • 1
    Ah, I forgot to capitalize None. Updated. – smiller Feb 25 at 19:31

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.