如何计算表格中的零值并将其写入新字段?


9

这是一个非常简单的任务,但是我无法理解正确的语法。

我有一个shapefile,其属性类似于以下内容:

FID Shape   FIELD1 FIELD2 FIELD3 ...
0   Polygon 0      1      0
1   Polygon 3      0      7
2   Polygon 3      4      7
...

字段的数量及其名称总是不同的。

我需要创建一个新字段(将其命名为NUM),并计算每行中的零个数。

输出示例:

FID Shape   FIELD1 FIELD2 FIELD3 NUM
0   Polygon 0      1      0      2
1   Polygon 3      0      7      1
2   Polygon 3      4      7      0

我知道如何创建一个新字段,但是在后续步骤中我不清楚。


工作代码:

#path is path to shape file
def a(path):
  fields = arcpy.ListFields(path,"FID_*") #FID_* is wildcard to select a fields name 
  arcpy.AddField_management(path, "NUM", "SHORT") #create a field with name NUM
  cursor= arcpy.UpdateCursor(path) 
  for row in cursor:
    count=0
    for field in fields: 
      a= row.getValue(field.name) #take a value 
      if a==0: #if value=0 then value=value+1
        count+=1
    row.setValue("NUM", count)
    cursor.updateRow(row)
  del row 
  del cursor

谢谢blah238,现在我可以吃蟒蛇了!

Answers:


8

这是执行此操作的一种方法的概述。我将把代码留给您作为练习。

  1. 读取所需的参数,例如输入 table
  2. 使用创建fields变量ListFields(),可以选择传入预期值field_type,例如Long
  3. NUMtable使用中添加一个新字段“ ”AddField()
  4. cursor使用创建一个变量UpdateCursor()
  5. 对于每一个rowcursor
    • 初始化count变量
    • 对于每一个fieldfields
      • 获取valuefield使用row.getValue()
      • 如果value等于0,则增加count1
    • 将添加字段的值设置为countusingrow.setValue()
    • 通话cursor.updateRow(),传入当前row
  6. 删除rowcursor变量

3

为此,您可以打开UpdateCursor并使用这样的代码(未经测试)遍历每一行。

rows = arcpy.UpdateCursor(path)   # path is your shapefile
for row in rows:
  count = 0
  if row.field1 == 0:
    count = count + 1
  if row.field2 == 0:
    count = count + 1
  if row.field3 == 0:
    count = count + 1
  row.num = count

如果您有field1到fieldN,那么您还需要遍历这些字段,并使用row.getValue()row.setValue()来处理变量而不是硬连接的字段名称。

更新

也许用我的答案作为提示来完成@ blah238的练习:-)


2
我喜欢以下更“ Pythonic”的表达式:count + = 1而不是count = count + 1,但这就是我。
Fezter

blah238在折磨我!!!
瓦西亚(Vasiya)2012年

我渴望成为更多的“ Pythonic”用户,因此下次一定要记住-这是我上次看到该语法时的意图-谢谢!
PolyGeo

@Vasiya对此感到抱歉,但我确定您已经听说过谚语“给男人一条鱼,他吃了一天,教一个男人钓鱼,并且他吃了一辈子” :)
blah238

@ blah238问题是我是草食动物,不吃蟒蛇!!!=)
Vasiya
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.