此代码将用于附加栅格单元数的多边形数据。例如,如果栅格是土地覆盖,则每个土地覆盖类型将会有一列,并且每个多边形内的相应单元格数将会有一列。该输出来自地理空间建模环境,因为Tabulate Raster在我正在使用的大型shape文件上不断崩溃。最终,我想要一个面积值,而不是一个细胞计数,这是下面的代码将实现的。使用if语句的Python for-loop
因此,代码将循环遍历shapefile属性,拉出原始计数字段,然后基于用户输入创建新字段(循环通过AddField使用用户输入名称+栅格值获取新字段名称),然后循环通过原始字段的值并计算新字段的用户指定区域值。本质上,我试图自动化添加字段,计算字段模型,我通常在模型构建器中批处理。
我很难找出计算新字段的正确逻辑。正如现在所写,它使用for循环获取原始字段,但只有最后一个原始字段值最终被使用,并且只填充最后一个新字段。我需要循环将第一个原始字段放在相应的新字段中,例如:
如果origFields =('NLCDV1','NLCDV2'...) 和addedFields =('KM2_LC1', 'KM2_LC2'...) 然后addField计算将以适当的值结束: 'KM2_LC1'= convert(其中convert =!NLCDV1!* cell) 'KM2_LC2'= convert(convert =!NLCDV2!* cell )等所有可能存在的值。
#User inputs the desired final units, loop through to find the desired units and calculates the new fields.
unit = arcpy.GetParameterAsText(7) #Must be: SqMeter, SqKm, Acres, Hectares, SqMi, or SqFt.
#User must know original units of raster, must be in Meters or Foot_US!!!
for field in origFields:
if rastunit == "Meter":
#To make square meters final area unit.
if unit == "SqMeter":
arcpy.CalculateField_management(inputPoly, addField, convert, "PYTHON_9.3")
#To convert square meters into Square Kilometers.
elif unit == "SqKm":
arcpy.CalculateField_management(inputPoly, addField, convertsqmsqkm, "PYTHON_9.3")
#To convert square meters into Acres.
elif unit == "Acres":
arcpy.CalculateField_management(inputPoly, addField, convertsqmac, "PYTHON_9.3")
#To convert square meters into Hectares.
elif unit == "Hectares":
arcpy.CalculateField_management(inputPoly, addField, convertsqmhec, "PYTHON_9.3")
#To convert square meters into Square Miles.
elif unit == "SqMi":
arcpy.CalculateField_management(inputPoly, addField, convertsqmsqmi, "PYTHON_9.3")
#To convert square meters into Square Feet.
elif unit == "SqFt":
arcpy.CalculateField_management(inputPoly, addField, convertsqmsqft, "PYTHON_9.3")
else:
print arcpy.AddWarning("Ineligible unit provided.")
elif rastunit == "Foot_US":
#To make square feet final area unit.
if unit == "SqFt":
arcpy.CalculateField_management(inputPoly, addField, convert, "PYTHON_9.3")
else:
print "This raster has the following units:" +rastunit+ ". If not in Foot_US or Meters, please reproject the raster."
我只需要弄清楚如何获得相应的原始字段以匹配新添加的字段。我正在考虑使用类似zip的东西(origField,addedField,calcs)。当我这样做,它给了我下面的输出:
(u'NLCDV1', 'KM2_LC1', '!NLCDV1! * 900.0')
(u'NLCDV2', 'KM2_LC2', '!NLCDV2! * 900.0')
(u'NLCDV3', 'KM2_LC3', '!NLCDV3! * 900.0')
(u'NLCDV4', 'KM2_LC4', '!NLCDV4! * 900.0')
(u'NLCDV5', 'KM2_LC5', '!NLCDV5! * 900.0')
(u'NLCDV7', 'KM2_LC7', '!NLCDV7! * 900.0')
(u'NLCDV8', 'KM2_LC8', '!NLCDV8! * 900.0')
(u'NLCDV9', 'KM2_LC9', '!NLCDV9! * 900.0')
这些线正是我需要的,但我不知道我是否可以使用这样的输出来填充字段,即使他们可以使用,我是新来的python和非常新的zip,所以我不知道如何使用它们。
任何与逻辑的帮助将不胜感激,并欢迎任何关于清理/重新排序的建议。就像我说的那样,当这一切都说完成时,我是新手。一旦我有了逻辑,我会很开心!感谢您的关注,如果我的代码过于复杂(如果是这种情况,请不要感到惊讶)。
请简化代码和问题。此外,你的代码缩进看起来很乱。 – martineau
我删除了大部分代码,只留下了我被卡住的for循环。希望这是令人愉快的。当我在PythonWin中调试它并且运行我的整个脚本时,缩进运行正常,以进行澄清。它读取光栅单元,选择适当的if语句,然后选择与用户的单元输入相匹配的if语句。 – user2547367