Select to view content in your preferred language

Field Calculator - find latest PCI

787
5
Jump to solution
10-12-2022 12:04 PM
RobertThomson
Frequent Contributor

I'd like to look at the fields pci2016 to pci2020 in each record and find the latest year that has a non zero value, then write that value to pci2021.

Is there something simple I can use Arcade or Python or is this beyond field calculator?

TIA

 

Latest PCI number.jpg

0 Kudos
2 Solutions

Accepted Solutions
JoshuaBixby
MVP Esteemed Contributor

Here is another approach besides using elif blocks:

update(!pci2016!, !pci2017!, !pci2018!, !pci2019!, !pci2020!)

# and code block
def update(pci2016, pci2017, pci2018, pci2019, pci2020):
    for newValue in (pci2020, pci2019, pci2018, pci2017, pci2016):
        if newValue != 0:  break
            
    return newValue

View solution in original post

RobertThomson
Frequent Contributor

This is the first one I tried, worked perfectly.  Thanks to all for responding.

View solution in original post

0 Kudos
5 Replies
RhettZufelt
MVP Notable Contributor

Field calculator will work.  Something like this should do it.  Of course, you will have to modify to match your data.  I didn't have enough "test" fields.

update(!pci2018!,!pci2019!, !pci2020!, !pci2021!)

# and code block 
def update(pci2018,pci2019,pci2020,pci2021):
    newval = None
    if pci2021 !=0:
        newval = pci2021
    elif pci2020 != 0:
        newval = pci2020
    elif pci2019 != 0:
        newval = pci2019        
    elif pci2018 != 0:
        newval = pci2018          
    if newval != 0:
        return newval
    else:
        return None 

R_

 

 

JoshuaBixby
MVP Esteemed Contributor

Here is another approach besides using elif blocks:

update(!pci2016!, !pci2017!, !pci2018!, !pci2019!, !pci2020!)

# and code block
def update(pci2016, pci2017, pci2018, pci2019, pci2020):
    for newValue in (pci2020, pci2019, pci2018, pci2017, pci2016):
        if newValue != 0:  break
            
    return newValue
RobertThomson
Frequent Contributor

This is the first one I tried, worked perfectly.  Thanks to all for responding.

0 Kudos
DanPatterson
MVP Esteemed Contributor

Or a numpy version

import numpy as np
def last(pci2016, pci2017, pci2018, pci2019, pci2020):
    """Do stuff"""
    flds = [pci2016, pci2017, pci2018, pci2019, pci2020]
    whr = np.nonzero(flds)[0][-1]  # first dimension last nonzero
    return flds[whr]
       
# -- first row in exampe data
last(!pci2016!, !pci2017!, !pci2018!, !pci2019!, !pci2020!)
88

... sort of retired...
RhettZufelt
MVP Notable Contributor

Or even Arcade:

When($feature.pci2020 != 0, $feature.pci2020,
      $feature.pci2019 != 0, $feature.pci2019,
      $feature.pci2018 !=0, $feature.pci2018,
      $feature.pci2017 != 0, $feature.pci2017,
      $feature.pci2016 !=0, $feature.pci2016, Null) 

R_