Here goes a 1D simple implementation. It shouldn't be difficult to generalize to more dimensions, as all the functions support axis argument:
>>> a=np.array([1, 2, 3, 5, 2]) >>> a.max() # This is the maximum value 5 >>> mask=np.zeros_like(a) >>> mask[np.argmax(a)]=1 >>> a=np.ma.masked_array(a, mask=mask) >>> a.max() # Second maximum value 3 I am using a masked array, so the structure of the array remains (ie, you can still use it in multi-dimensional arrays). I could have deleted de value, but then that wouldn't be useful for your case. On Fri, Aug 3, 2012 at 4:18 PM, Jim Vickroy <jim.vick...@noaa.gov> wrote: > Hello everyone, > > I'm trying to determine the 2 greatest values, in a 3-d array, along one > axis. > > 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 > (xcnt)) > 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. > > Thanks, > -- jv > _______________________________________________ > NumPy-Discussion mailing list > NumPy-Discussion@scipy.org > http://mail.scipy.org/mailman/listinfo/numpy-discussion _______________________________________________ NumPy-Discussion mailing list NumPy-Discussion@scipy.org http://mail.scipy.org/mailman/listinfo/numpy-discussion