TransWikia.com

When calculating a field in an attribute table, how can I find one value out of many fields when every other field has a null value?

Geographic Information Systems Asked on January 13, 2021

I have 4,018 rows of data with about 50 fields. About 45 of those fields are the same variable, but the data came from different layers, so out of those 45 fields, only one has a value for the row, the rest are null. I just need the actual value in my final field. I used a string wildcard to identify the right fields. This code returns NULL for every row.

def n():
    import arcpy
    fields = arcpy.ListFields('Extract_fires')
    for f in fields:
        if f == 'AVGPRE*' and f is not None:
            return(f)

One Answer

You can solve this using da.UpdateCursor:

import arcpy

fc = r'C:folderdata.gdbpolygons123' #Change
field_to_hold_the_nonNonevalue = 'somefield' #Change
#List all fields starting with AVGPRE, and add the field to update last in list
fieldlist = [f.name for f in arcpy.ListFields(fc, 'AVGPRE*') if f.name != field_to_hold_the_nonNonevalue] + [field_to_hold_the_nonNonevalue]

with arcpy.da.UpdateCursor(fc, fieldlist) as cursor:
    for row in cursor: #For each row in the attribute table 
        #row is now a tuple of all fields values, for example (None, None, 1, None, ... None)
        value = [val for val in row[:-1] if val is not None][0] #Pick the first (index 0) non-None value in the row
        row[-1] = value #Set the last field in fieldlist to value
        cursor.updateRow(row)

Correct answer by BERA on January 13, 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