Python If Function for Ranged Field
Actually this is a Python in GIS, so I use table in my Arcgis and try to count the field and divided it by using category.
I have Field named Elevation the data contain integer example :
1 - 2
3 - 6
2 - 3
8.5 - 12
11 - 12
I need to categorize it using rule that
if Elevation < 1 then Index = 0.3 ,if Elevation = 2 - 3 Index = 0.6, if Elevation > 3 Index = 1
I have this code :
def Reclass( Elevation ):
r_min, r_max = (float(s.strip()) for s in Elevation.split('-'))
print "r_min: {0}, r_max: {1}".format(r_min,r_max)
if r_min < 1 and r_max < 1:
return 0.333
elif r_min >= 1 and r_max >= 1 and r_min <= 3 and r_max <= 3:
return 0.666
elif r_min > 3 and r_max > 3:
return 1
elif r_min <= 3 and r_max > 3:
return 1
else:
return 999
my question is how to strip it, and categorized it using my rule above? Thanks before
I have borrowed code from you and @jpmc26 below. This code (minus the print
statements that are just there for testing) should work for you in the Field Calculator of ArcMap but it is simply Python code. The problem is that you have not told us what you want to do when the two ends of a range fall into different categories so for now I have used an else
statement to put out 999.
def Reclass( Elevation ):
r_min, r_max = (float(s.strip()) for s in Elevation.split('-'))
print "r_min: {0}, r_max: {1}".format(r_min,r_max)
if r_min < 1 and r_max < 1:
return 0.333
elif r_min >= 1 and r_max >= 1 and r_min <= 3 and r_max <= 3:
return 0.666
elif r_min > 3 and r_max > 3:
return 1
else:
return 999
print Reclass("0 - 1.1")
print Reclass("5.2 - 10")
print Reclass("2 - 3")
print Reclass("0 - 0")
Based on comments, your field is a string that contains ranges of the form you describe above.
Firstly, this is horrible database design. The minimum and maximum should be separate columns of integer types. shakes fist at ESRI more for discouraging good database design
Furthermore, your rule is insufficient for dealing with a range. A range check would either need to compare against either 1 end of the range or both ends. So you will have to clarify exactly what you want for your "indexing" rule.
Given that you have strings representing ranges, your only option is to parse the range into its minimum and maximum and work with those. That's not too hard in Python:
>>> r = "3 - 6"
>>> r_min, r_max = (int(s.strip()) for s in r.split('-'))
>>> r_min
3
>>> r_max
6
What does this do?
It's pretty simple, actually. It splits the string by the -
. Then it loops over the resulting list, and each element has its leading and trailing whitespace removed and is then converted into an int
. Finally, Python unpacks the generator on the right to fill in the variables on the left.
Be aware that malformed data will cause errors.
Once you've clarified your "index" rule, you can figure out how to use this minimum and maximum to get your "index".
链接地址: http://www.djcxy.com/p/76634.html上一篇: 了解使用d [key] =无
下一篇: Python如果函数为远程字段