Wednesday, December 12, 2012

Finding and Changing Max Value in Numpy Array

Today, I answered a forum question about finding and changing a numpy array.  You can use the max() and the where() in the numpy to search for values in your array and change them using loops.

You can download a very simple example here.

Here is the simple code:

import numpy
myarray = numpy.array([[  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.6,   4.5,   2.7,   3.6,   6.7,   4.5],
                       [  1.2,   2.3,   7.2,   6.3,   2.2,   2.0 ],
                       [  1.3,   2.0,  -99.0,    9.6,  -99.0,    1.2]
                       ]
                      )
print myarray
maxValue = myarray.max()

itemindex = numpy.where(myarray >= maxValue)

for i in xrange(0, len(itemindex[0])):
    array1 = itemindex[0]
    array2 = itemindex[1]
    myarray[array1[i]][array2[i]] = 0

print myarray




Here we have the numpy array and find the array's maximum value.  Then using the where(), the location in the array are given back.  From there, the code then changes the values in the 2-D array from the maximum value back to zero.

Enjoy

1 comment:

Charles Morton said...

The great thing about Python/NumPy is that you don't have to use loops for something like this.
Make sure to read the indexing documentation for the details.

Just call: myarray[myarray==myarray.max()] = 0