I want to write a function which takes in two arguments (from two rasters) and compare those 2 values against a set of hard coded pair values inside function. Then return a value which i want to use to generate a new grid. I am not quite there to complete the function. Any suggestions?
def grid(val1, val2):
table = {'10','1':'75','10,2':'75','10,3':'83','10,4':'87'}
for i, j, k in table.iteritems():
if val1 == i:
if val2 == j:
val = k
return val
t = grid(10,1)
1 Answer 1
You should be able to fairly easily grab your raster as a numpy array in ArcGIS (and for that matter put it back).
Then borrow liberally from the answer to this stack overflow question.
In your case you have two grids, each with their own corresponding value. Tuples can act as a dictionary key, so that's what I'd suggest in your case. Then we have a simple bit of code:
#grid_1 and grid_2 are numpy arrays of the input rasters
import numpy as np
table = {(10, 1):75,
(10, 2):75,
(10, 3):83,
(10, 4):87}
#assuming that the input grids are the same dimensions
output_grid = np.ones(grid_1.shape, dtype=np.int) * -9999 #usually a good value for null
for k, v in table.iteritems(): #k will be a tuple
output_grid[[grid_1 == k[0]] and [grid_2 == k[1]]] = v
-
Thanks. I tried to test it with simple 10 and 1 value and got following error: TypeError: 'int' object does not support item assignment at:
grid_1[grid_1==k[0]] = v
Ibe– Ibe2012年11月15日 00:41:59 +00:00Commented Nov 15, 2012 at 0:41 -
Sorry;
grid_1
should be the entire raster as a numpy array (this will replace every instance of the number in the grid with the value fromtable
)om_henners– om_henners2012年11月15日 01:02:15 +00:00Commented Nov 15, 2012 at 1:02 -
Sorry, re-read the question; given you want a different grid as output I've modified the function above to return a separate grid.om_henners– om_henners2012年11月16日 04:07:33 +00:00Commented Nov 16, 2012 at 4:07
-
It worked. I tried to save the final grid but got following error:
ValueError: Argument in_array: Array type is not supported.
outgrid = np.ones(lu.shape, dtype=np.int) * -9999 for k,v in table.iteritems(): outgrid[[grid1 == k[0]] and [grid2 == k[1]]] = v print outgrid myArray = arcpy.NumPyArrayToRaster(outgrid) myArray.save("grid3")
Ibe– Ibe2012年11月17日 20:58:57 +00:00Commented Nov 17, 2012 at 20:58 -
-9999 caused that problem while saving numpy array as raster. Anyhow I checked the result and there is something wrong with how iteration is done. I used a full table with 40 records but final output only have 4 integer values. I am still trying to understand whether it is caused by 'iteritems' or tuple comparison.Ibe– Ibe2012年11月18日 01:43:09 +00:00Commented Nov 18, 2012 at 1:43
Explore related questions
See similar questions with these tags.