def Reclass(site_code): if route_ty_1 == 'Bus': return 338 elif route_ty_1 == 'LIGHT RAIL': return 281 elif route_ty_1 == 'METRO': return 335 elif route_ty_1 == 'Rail': return 282 elif route_ty_1 == 'Commuter Bus': return 336
Reclass(!site_code!)
def Reclass(route_ty_1): if route_ty_1 == 'Bus': return 338 elif route_ty_1 == 'LIGHT RAIL': return 281 elif route_ty_1 == 'METRO': return 335 elif route_ty_1 == 'Rail': return 282 elif route_ty_1 == 'Commuter Bus': return 336
def Reclass(site_code): site_code=site_code.lower().strip() if site_code == 'bus': return 338 elif site_code == 'light rail': return 281 elif site_code == 'metro': return 335 elif site_code == 'rail': return 282 elif site_code == 'commuter bus': return 336 else: return 0
Hello David,
There are some interesting options here.
That being said, I often use the else if method. If I may suggest a few things, I would add a .lower() (makes it case insensitive) and a .strip() (gets rid of any leading or trailing whitespace) to make sure you are matching as many of the cases as possible. I'd also add a else to catch any records that don't match at all.def Reclass(site_code): site_code=site_code.lower().strip() if site_code == 'bus': return 338 elif site_code == 'light rail': return 281 elif site_code == 'metro': return 335 elif site_code == 'rail': return 282 elif site_code == 'commuter bus': return 336 else: return 0
Good luck!
Thanks Joshua--should there be anything in the .lower and .strip parentheses?
ERROR 000539: Error running expression: Reclass(0) Traceback (most recent call last): File "<expression>", line 1, in <module> File "<string>", line 2, in Reclass AttributeError: 'int' object has no attribute 'lower' Failed to execute (CalculateField).
Nope!
If you want, you can specify characters you want removed from the front and end of a string with the strip() function, but leaving it empty will remove whitespace by default.
Thanks--I am getting the following errors:ERROR 000539: Error running expression: Reclass(0) Traceback (most recent call last): File "<expression>", line 1, in <module> File "<string>", line 2, in Reclass AttributeError: 'int' object has no attribute 'lower' Failed to execute (CalculateField).
def Reclass(inputTansitType): inputTansitType=inputTansitType.lower().strip() if inputTansitType== 'bus': return 338 elif inputTansitType== 'light rail': return 281 elif inputTansitType== 'metro': return 335 elif inputTansitType== 'rail': return 282 elif inputTansitType== 'commuter bus': return 336 else: return 0
reclass_dict = {'bus': 338, 'light rail': 281, 'metro': 335, 'rail': 282, 'commuter bus': 336, } def Reclass(inputTansitType): inputTansitType = inputTansitType.lower().strip() try: return reclass_dict[inputTansitType] except: return 0