如何使用SearchCursor工具从表中提取特定值

0 投票
1 回答
4110 浏览
提问于 2025-04-18 17:45

我知道之前有人问过类似的问题,但因为我对Python还很陌生,所以没办法把其他讨论和建议应用到我的情况中!

我正在尝试写一个Python脚本,从一个表格中提取特定的值:这个表格是一个关于不同水深的硝酸盐值的大集合,这些值被放在表格的列里。因为我只需要表面和最深点的值,所以我想在行中搜索,提取最后一个不是0的值。我已经开始用SearchCursor工具写脚本,但在想要搜索第一个0值的地方卡住了,然后想回去打印前一列的值……有没有人知道怎么解决这个问题?

import arcpy

# Set the Workspace
arcpy.env.workspace = "D:\Teresa\Kerstin\SouthernOcean\03_workspace\Teresa"

# Make table
table = "C:/Users/theidema/Desktop/OxzUti_GridP_Annual.csv"

# Create the search cursor
cursor = arcpy.SearchCursor(Table)

# Iterate through the rows
row = cursor.next()
while row:
    print (row.getValue(field))
    row = cursor.next()

1 个回答

0

一眼看过去,我发现了三个错误。

首先,SearchCursor()里的“Table”这个参数是大写的,而你的变量“table”是小写的。这个是区分大小写的,所以它们需要一致。

其次,你在打印语句中用了“field”作为参数,但这个变量并没有定义。在While循环之前,定义一下这个变量,比如:field = "你想搜索的字段名称"

最后,在你的While循环中,不需要重新定义变量“row”。只需要用cursor.next(),把“row = ”去掉就行了。(在循环之前,row = cursor.next()是用来判断是否还有下一行的,只要有下一行就会继续循环,当没有下一行时就会变成False,循环就结束了。)

哦对了!我注意到你的工作空间不是文件地理数据库。如果我是你,我会使用GDB,特别是因为要素类不能在GDB之外存在。不过如果你用的是Shapefile,可能也能用。

import arcpy

# Set the Workspace
arcpy.env.workspace = "D:\Teresa\Kerstin\SouthernOcean\03_workspace\Teresa" 
#If "Teresa" is a GDB, append ".gdb"

# Define variables
table = "C:/Users/theidema/Desktop/OxzUti_GridP_Annual.csv"
field = "" #Add the Field Name that you want to Search

# Call your CSV in SearchCursor
cursor = arcpy.SearchCursor(table)

# Iterate through the rows
row = cursor.next()
while row:
    print (row.getValue(field))
    cursor.next()

撰写回答