NYGeog

Geography, GIS, Geospatial, NYC, etc.

Thursday, February 16, 2012

Python Code Block - Population Density (numerator zero and string to numeric)

Okay, so this morning, I've been dealing with two things. Well the first is that my ACS Census 2006-2010 conversion scripts create string fields for the variables. They should be numeric. I'll deal with that on its own. But this challenge was sort of interesting b/c it required two things. First off, I needed to calculate Population Density (per sq. km) but I've been having trouble with Python dealing with zero's (0) in the numerator for division when my added Field is non-nullable (I think if you add a field after the initial feature class creation you can't allow a field to be nullable, need to check on that though) and then converting and using a string value in my Code Block. I did a bunch of things wrong at first. My colleague's friend helped me figure this out over gchat by showing him my first code that didn't work. So thanks to him, though I don't know his name, but know he works at the EPA or did when my colleague was there. First off, I was only using a space, no comma in my Expression between !field_names!. Secondly, I noticed I needed to set my string equal using == rather than = or is. So here's the code that worked for me. Use it for Population Density Calculations just be sure to get rid of the float and the quotes if your Population variable is in fact numeric.

!B01003001E! is a string of the total population
!ALAND10! is land area in sq. meters (double)

Expression:

Calc(!B01003001E!, !ALAND10!)

Code Block:

def Calc(pop, land):
if pop == '0':
return 0
else:
return float(pop)/(land*0.000001)