TransWikia.com

Calculating fields (multiple) with different conditions for each field using ArcGIS Pro

Geographic Information Systems Asked on December 3, 2021

I have a population dataset where I want to reclassify the age groups and include gender. I have the field “gender”, 1 for men and 2 for women, and the field “age”. One row for each person in the dataset.

I want 5-year age groups based on gender: Men 0-4 years (M_0_4), men 5-9 (M_0_9)…up to M95_99 and W_0_4, W_5_9 and so on. I can do this manually for each field with this code:

M_0_4=
    Reclass(!gender!, !age!)

    #codeblock:
    def Reclass(gender, age):
       if (gender = 1 and age >= 0 and age <= 4):
            return 1
        else:
            return 0

Is there anyway to do this for all fields using calculate field (multiple) in one go? Each field would need a different condition. I have tried making a separate expression for each field and then just copying the codeblock for each and changing the expression name and conditions without luck, e.g:

#expressions:
M_0_4=
  m_0_4(!gender!, !age!)
M_5_9=
  m_5_9(!gender!, !age!)

#codeblock:
def m_0_4(gender, age):
   if (gender = 1 and age >= 0 and age <= 4):
        return 1
   else:
        return 0

def m_5_9(gender, age):
   if (gender = 1 and age >= 5 and age <= 9):
       return 1
   else:
       return 0

One Answer

I'm a bit confused on what you want. The way I would do this is one new field say called 'age_bin' with values like M_0_4 or F_35_40 for each row.

But you keep mentioning multiple fields and the your code is returning 1 or 0 which makes me think you want a field per gender/age combo with a 1 or 0 denoting whether or not the row is in that bin. I can't understand why you would do it that way personally as it will make your attribute table way larger and harder to interpret than a single column with binned data.

I would use this little bit of code to create the strings to represent the bins in a single field:

def binning(!age!,!gender!):
    rounded = int(5 * round(float(age)/5))
    if rounded > age:
        return gender + "_" + str(rounded-5) + "_"+ str(rounded-1)
    else:
        return gender + "_" + str(rounded) + "_"+ str(rounded+4)

If age = 12 the rounded value is 10. 10 is less than 12 so age must be in bin M_10_14.

If age = 28 the rounded value is 30. 30 is greater than 29 so age must be in bin M_25_29

If age = 45 the rounded value is 45. 45 is not less than 45 so the age must be in bin M_45_49.

I haven't tested it in Arc, but it works in Python 3 Jupyter Notebook.

Answered by Hyder Al Hassani on December 3, 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