AnsweredAssumed Answered

Updating table fields from a raster file

Question asked by r.brso on Dec 5, 2018
Latest reply on Dec 11, 2018 by xander_bakker

Hi there! I have some raster files in grid format with signed integer pixels in which I want to add some fields in their table then compute values with some formulas in the new fields. I managed to add the fields but I'm struggling with the second part. I tried with arcpy.da.UpdateCursor but it returns a RuntimeError: 'in_table' is not a table or a feature class. It seems clear for me that I can not use this function with raster file. Is there a way to compute the values directly in the raster or do I have to try a different approach? How?

 

The code is:

import arcpy as ap
import os
import random_function as rf # change name after
from arcpy.sa import *

if ap.CheckExtension('Spatial') == 'Available':
     ap.CheckOutExtension('Spatial')
else:
     print('Spatial Analyst extension is not available')

# Setting environments & paths
ap.env.workspace = os.path.join("D:\\", "master", "_thesis_data")
ap.env.scratchWorkspace = os.path.join(ap.env.workspace, "temp")
ap.env.overwriteOutput = True
inp_ws = ap.env.workspace
temp_ws = ap.env.scratchWorkspace
lu_folder = os.path.join(inp_ws, "lu")

lu_scenarios = []
for dirpath, dirnames, filenames in ap.da.Walk(lu_folder, datatype='RasterDataset'):
     for f in filenames:
          lu_scenarios.append(os.path.join(dirpath,f))

# Setting input data
climate = Raster("climate_c")
clim_soil = Raster("rc_climsoil_c")
tbl_uSOCr = os.path.join(inp_ws, "uSOCr.txt")
tbl_uSOCf = os.path.join(inp_ws, "uSOCf.txt")
tbl_uBCi = os.path.join(inp_ws, "uBCi.txt")

for (sc, lu_sc) in enumerate(lu_scenarios):
     lu = Raster(lu_sc)
     clim_lu = climate + lu
     soc_f1k = ReclassByTable(clim_lu, tbl_uSOCf, "id", "id", "soc_factor")
     soc_r1k = ReclassByTable(clim_soil, tbl_uSOCr, "id", "id", "soc_ref")
     soc_1k = (soc_f1k*soc_r1k)/1000
     bc_1k = ReclassByTable(clim_lu, tbl_uBCi, "id", "id", "bcs")          
     tc_1k = (soc_1k + bc_1k)
     tc_1k_new_fields = ["tc", "tot_ha", "tot_cs"]
     for field in tc_1k_new_fields:
          ap.AddField_management(tc_1k, field, "FLOAT", 12, 4)
     with ap.da.UpdateCursor(tc_1k, "*") as cursor:
          tc_all_fields = [f.name for f in arcpy.ListFields(tc_1k)]               
          VALUE, COUNT, tc, tot_ha, tot_cs = row[1], row[2], row[3], row[4], row[5]
                 for row in cursor:
                    tc = VALUE/1000
                    tot_ha = COUNT*2500 
                    tot_cs = tc*tot_ha 
                    cursor.updateRow(row)                                   
                    
     if ap.GetRasterProperties_management(tc_1k, "ALLNODATA"):
          tc_1k.save(temp_ws + "\\" + "0sc" + str(sc) + "_tc" + str(mc_counter+1)) # ==> TESTING DATA!!!
     print tc_1k

 

Thanks again!

Outcomes