How can I fill in null values in a field based on the previous value found in that same field?..

963
5
08-04-2019 01:31 PM
IsaíasSantos
New Contributor II

I have a table where the information of a field has empty values and I want to fill them with the value of the upper cell

   

5 Replies
XanderBakker
Esri Esteemed Contributor

Hi DanielFirst ,

I would probably use a python script for this and run through the records and update them based on the previously known value. Would that be an option for you?

IsaíasSantos
New Contributor II

Surely with Python, he used the following code but fill in the empty cells

previous = None

def calcowner (owner):
global preview
val = previous if ownerval is None more ownerval
prevval = val
val return

calcowner (! Owner!)

How you could structure the code to work

0 Kudos
XanderBakker
Esri Esteemed Contributor

Hi Isaías Santos ,

I notice that you are using ArcMap. Sometimes using the FieldCalculator makes things a bit more complicated. You can open the Python window in ArcMap and symply edit and past the code below:

fc = 'Name of your feature class in TOC goes here' # edit this!
fld = 'Owner' # name of your field to update
prev = None
with arcpy.da.UpdateCursor(fc, (fld)) as curs:
    for row in curs:
        if row[0] == None:
            row[0] = prev
        else:
            prev = row[0]
        curs.updateRow(row)

Notice that this code will update your data, so it will be best to test on a copy of your data. 

Remember to change the name of your featuresclass on the first row as it appears in the table of content in ArcMap.

In the screenshot above you can see on the left of the screen that my featureclass is named "test", which is what I used on the first line of the code (lower center/right). My field is called "myField" (line 2 in code) and in the table you can see in field "Test" what the initial values were before running the script. Notice also that if the first record has no value, it will not be changed, since there is no initial value set. If you want to change this you can edit this on line 3 but doing something like:

prev = 'my initial value'

curtvprice
MVP Esteemed Contributor

Isaías Santos you posted to the ModelBuilder space so I here is an example to use Xander's cursor code in the Calculate Value tool. A little bit of Python can go a long way in ModelBuilder.

# Calculate Value tool

# Expression (Feature layer and Field are model variables)
f(r"%Feature layer%", "%Field%")

# Code Block
def f(fc, fld):
    prev = None
    with arcpy.da.UpdateCursor(fc, (fld)) as curs:
        for row in curs:
            if row[0] == None:
                row[0] = prev
            else:
                prev = row[0]
            curs.updateRow(row)
    return(fc)

# Data Type
Feature Layer‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
IsaíasSantos
New Contributor II

Muchas gracias!

Lo probaré.

0 Kudos