I have a table that has Null values and I would like to insert a portion in my script to calculate these Null values to 0 in only a few of my columns in my table.
Here is my script so far:
with arcpy.da.UpdateCursor(target, "ELEM_STUD") as cursor:
for row in cursor:
row[0] = None
cursor.updateRow(row)
del row
Target is my table, which is a parameter that is defined prior to this portion of my code.
The error that I am getting is in the first line, stating that 'ELEM_STUD' is not defined. That is the first of multiple fields I would like this script to run through.
I have also tried to add removeNull ("ELEM_STUD")
after my cursor and haven't had any luck there either.
2 Answers 2
you can work on more than one fiel at the time, and use some list comprehension to go through your row
with arcpy.da.UpdateCursor(target, ("ELEM_STUD","second_field","thirdfield") ) as cursor:
for row in cursor:
newrow = [0 if x == None else x for x in row]
cursor.updateRow(newrow)
-
This did the trick, much appreciated.forrestchev– forrestchev2016年03月15日 14:53:16 +00:00Commented Mar 15, 2016 at 14:53
Make sure the target
does refer to a proper feature class.
You need to check whether your field value is None first. If yes, then update with 0.
with arcpy.da.UpdateCursor(target, "ELEM_STUD") as cursor:
for row in cursor:
if row[0] == None:
row[0] = 0
cursor.updateRow(row)
-
Alex, that works great, thank you very much. I have 9 more fields, what would be the best way to update those fields? Copying the cursor seems inefficient to me but the only way I can think of in this case...forrestchev– forrestchev2016年03月15日 14:31:25 +00:00Commented Mar 15, 2016 at 14:31
-
@forrestchev, you may add a list of fields for the second parameter of the cursor and do conditional checks on those for None.artwork21– artwork212016年03月15日 14:36:32 +00:00Commented Mar 15, 2016 at 14:36
Explore related questions
See similar questions with these tags.