« Lougheed House | Main | Awk csv and cut the header... »

Simple median in python

Yesterday I was doing some python scripting for work on [GALFACTS] and I wanted to take the median of an array. I know I could simply use the [numpy] function but I specifically wanted to alter the behaviour to skip NaNs (in the end I ended up doing this a different way using the isnan functionality) and so I wrote a short script to calculate the median, thought I'd post it as a short example of some simple python programming / you never know if it will come in handy again (for me or anyone else). The full script can be retrieve from my [research script dump], oh and below:


#Function to determine the median of an passed array/list of number
def takemedian(inputvalues):
     sortedvalues = sorted(inputvalues) #sort values
     total_len = len(sortedvalues)
     if (total_len % 2) == 1:
         return sortedvalues[((total_len+1)/2)-1]
     else:
         upperval = sortedvalues[(total_len)/2]
         lowerval = sortedvalues[(total_len/2)-1]
         return (float(lowerval + upperval)) / 2


#test function
def validatemedian(correct, takemedianvalue):
     print "Test Median is: %.2f, takemedian function value is: %.2f, Is Correct? %s" % (correct, takemedianvalue, correct==takemedianvalue)

#test what the ouput is
validatemedian(5.0, takemedian([0,1,2,3,4,5,6,7,8,9,10]))

TrackBack

TrackBack URL for this entry:
http://krioma.net/cgi-bin/MT-3.38/mt-tb.cgi/470

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)

About

This page contains a single entry from the blog posted on November 22, 2010 5:58 AM.

The previous post in this blog was Lougheed House.

The next post in this blog is Awk csv and cut the header....

Many more can be found on the main index page or by looking through the archives.

Get Firefox! Valid XHTML 1.0! Valid CSS! RSS Feed BlogUniverse - listed Powered by Apache Creative Commons License ringsofsaturnrock's Most Interesting Photos on Flickriver

Powered by
Movable Type 3.38