determining maximum cell from a Numpy array

980
6
12-06-2012 11:12 PM
BarbaraLokes
New Contributor
hello

i have a large numpy array and i would like to write a python script for assigning zero (0) to every maximum cell in every four adjacent cells. For example, see figure below:

[ATTACH=CONFIG]19775[/ATTACH]


Any help would be very much appreciated, thanks in advance!
Tags (2)
0 Kudos
6 Replies
AndrewChapkowski
Esri Regular Contributor
You can find a value positions by doing the following:
   itemindex=numpy.where(array==item)

Then change your values.

You can find the max value by doing the following:
>>> from numpy import *
>>> a = array([10,20,30])
>>> a.max()
30
>>> a = array([[10,50,30],[60,20,40]])
>>> a.max()
60


Hope this helps.  You can find more information about numpy by going to the scipy.org site.
0 Kudos
RaphaelR
Occasional Contributor II
tried this with a sample 6x6 grid. i´d really like to know if there´s a better way (i´m sure there is) using more numpy/scipy (tried that at first but couldn´t really get it working).
anyways...
in:
[[  5.4   7.5   2.2   8.5   8.6   7.5]
 [  7.7   3.5   1.4   9.6   8.5   5.5]
 [  5.2   6.1   8.6   6.7   4.3   6.8]
 [  9.3   4.5   2.7   3.6   6.7   4.5]
 [  1.2   2.3   7.2   6.3   2.2   2. ]
 [  1.3   2.  -99.    4.  -99.    1.2]]


nrows=6
ncols=6
for row in range(0, nrows -1, 1):
    for col in range(0, ncols -1, 1):
        # current 2x2 subgrid        
        curgrid = {grid[row,col]:(row,col), grid[row, col+1]:(row, col+1),\
                   grid[row+1,col]:(row+1,col), grid[row+1, col+1]:(row+1, col+1)}
        # set max of current subgrid in the totalgrid to 0
        grid[curgrid[max(curgrid)]] = 0


out:
[[  5.4   0.    2.2   8.5   0.    7.5]
 [  0.    3.5   1.4   0.    0.    5.5]
 [  5.2   0.    0.    0.    0.    0. ]
 [  0.    0.    2.7   0.    0.    0. ]
 [  1.2   0.    0.    0.    0.    0. ]
 [  1.3   0.  -99.    0.  -99.    0. ]]
0 Kudos
AndrewChapkowski
Esri Regular Contributor
Your list syntax is incorrect.  You need to use commas between values.

You can find out about type formatting at python.org.

Thanks

Andrew
0 Kudos
RaphaelR
Occasional Contributor II
the input is an array
print type(grid)
<type 'numpy.ndarray'>

0 Kudos
AndrewChapkowski
Esri Regular Contributor
Try putting commas after each number.

My code worked then.
0 Kudos
RaphaelR
Occasional Contributor II
the code works for me as well.
i just said that i would also be very interested in a more/only numpy-based approach.
0 Kudos