TransWikia.com

Script removes all data from fields when using custom function in Field calculator

Geographic Information Systems Asked by Darren De Lange on July 30, 2021

I am trying to clear entries in columns using the field calculator but with my current script, it removes all the data from all the rows. Basically, if the Historical column is equal to ‘Historical Survey’, I want it to replace the field text with '<Null>' but if the historical column is equal to ‘Most recent survey’, I want it to keep the text in that cell.

The full script is:

Expression line: reclass(!Key_Biomec!,!Historical!)

def reclass(Key_Biomec, Historical):
  if (Historical == 'Historical Survey'):
    return '<Null>'
  

Currently, this script removes all the data from the fields, no matter if they are labelled ‘Historical Surveys’ or ‘Most recent surveys’. How to solve this issue?

2 Answers

You should always check to see that Calculate Field functions return a value in all possible condition paths. One way to do this is to use a code pattern that initializes the return value and uses if statements to alter it before a singleton return:

def reclass(key_biomec, historical):
    result = key_biomec
    if (historical == 'Historical Survey'):
        result = '<Null>' # or None, if an actual NULL value is needed
    return result

Note that Python best practice is to always use four spaces for indent and reserve uppercase names for object declaration.

Correct answer by Vince on July 30, 2021

Your code must be like below:

Expression line: reclass(!Historical!)

def reclass(Historical):
  if (Historical == 'Historical Survey'):
    return 'Null'
  else:
    return Historical

Answered by Kinan AlQassem on July 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP