[Numpy-discussion] 2 greatest values, in a 3-d array, along one axis

Jim Vickroy jim.vickroy at noaa.gov
Fri Aug 3 11:18:12 EDT 2012

Hello everyone,

I'm trying to determine the 2 greatest values, in a 3-d array, along one 

Here is an approach:

# ------------------------------------------------------
# procedure to determine greatest 2 values for 3rd dimension of 3-d 
array ...
import numpy, numpy.ma
xcnt, ycnt, zcnt   = 2,3,4 # actual case is (1024, 1024, 8)
p0                 = numpy.empty ((xcnt,ycnt,zcnt))
for z in range (zcnt) : p0[:,:,z] = z*z
zaxis              = 2                                            # max 
values to be determined for 3rd axis
p0max              = numpy.max (p0, axis=zaxis)                   # max 
values for zaxis
maxindices         = numpy.argmax (p0, axis=zaxis)                # 
indices of max values
p1                 = p0.copy()                                    # work 
array to scan for 2nd highest values
j, i               = numpy.meshgrid (numpy.arange (ycnt), numpy.arange 
p1[i,j,maxindices] = numpy.NaN                                    # flag 
all max values
p1                 = numpy.ma.masked_where (numpy.isnan (p1), p1) # hide 
all max values
p1max              = numpy.max (p1, axis=zaxis)                   # 2nd 
highest values for zaxis
# additional code to analyze p0max and p1max goes here
# ------------------------------------------------------

I would appreciate feedback on a simpler approach -- e.g., one that does 
not require masked arrays and or use of magic values like NaN.

-- jv

More information about the NumPy-Discussion mailing list