需求

2011-2019年3月逐日数据,提取到点属性表后再输出Excel
由于总列数超过255,故只能一年31个数据输出一次Excel,然后清空属性表开始下一次提取

代码

# -*- coding: utf-8 -*-
# 把itvdi按点提取到表格 因为table to excel工具只能支持256列 所以每一年一输出excel并且清空table
# ---------------------------------------------------------------------------
import arcpy
from arcpy.sa import *
import os

# 点shapefile
point_shp_file = r"E:\IrrigationFinal\00SHP\HNfish.shp"
# 临时shapefile
temp_shp_file = r"E:\IrrigationFinal\00SHP\HNfish_temp.shp" # 副本的名称
arcpy.CopyFeatures_management(point_shp_file, temp_shp_file)


for year in range(2011, 2020):#Python切片 含前不含后
    arcpy.env.workspace = r"E:\IrrigationFinal\03iTVDI11_22" + "\\" + str(year)  # 环境设置
    rasterlist = arcpy.ListRasters("*", "dat")  # dat拓展名
    for rastername in rasterlist:#每一年每一天数据循环提取
        inRasterList = [[rastername, os.path.basename(rastername)[5:15]]] 
        arcpy.gp.ExtractMultiValuesToPoints_sa(temp_shp_file, inRasterList, "NONE")
        print(rastername)
    arcpy.TableToExcel_conversion(temp_shp_file, r"E:\IrrigationFinal\iTVDI" + str(year) + ".xls")#提取完一年后输出Excel
    fieldList = arcpy.ListFields(temp_shp_file)
    for field in fieldList:# 删除多余的字段
        if field.name != 'FID' and field.name != 'Shape' and field.name != 'Id' and field.name != 'num':
                arcpy.DeleteField_management(temp_shp_file, field.name)
# 删除临时shp
arcpy.Delete_management(temp_shp_file)
print("OK!")

DeBug

  1. 为了增加稳定性,采用CopyFeatures创建副本点shp文件来进行运算
  2. 因为使用了复制,或者其他原因,循环到下一个年份,或者对其他数据提取点再进行提取时,FID字段会变化,导致不同数据无法匹配
  3. 因此需要创建一个唯一编号字段num,之后的coding中代替FID的地位,代码如下:
import arcpy
point_shp_file = r"E:\IrrigationFinal\00SHP\HNfish.shp"
arcpy.AddField_management(point_shp_file, "num", "LONG")
with arcpy.da.UpdateCursor(point_shp_file, ["num", "SHAPE@"]) as cursor:
    for i, row in enumerate(cursor, start=1):  # 使用enumerate来计数,并从1开始
        row[0] = i  # 将计数器的值赋给新字段
        cursor.updateRow(row)  # 更新行

4.InRasterList变量的简单写法inRasterList = [(rastername, os.path.basename(rastername)[9:13])]
5.清空字段部分的简单写法`

    # 清空新加入的字段
    fieldList = [f.name for f in arcpy.ListFields(temp_shp_file) if f.name not in ['FID', 'Shape', 'Id', 'num']]
    arcpy.DeleteField_management(temp_shp_file, fieldList)
Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐