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):
&nbsp&nbsp&nbsp&nbsp sortedvalues = sorted(inputvalues) #sort values
&nbsp&nbsp&nbsp&nbsp total_len = len(sortedvalues)
&nbsp&nbsp&nbsp&nbsp if (total_len % 2) == 1:
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp return sortedvalues[((total_len+1)/2)-1]
&nbsp&nbsp&nbsp&nbsp else:
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp upperval = sortedvalues[(total_len)/2]
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp lowerval = sortedvalues[(total_len/2)-1]
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp return (float(lowerval + upperval)) / 2
#test function
def validatemedian(correct, takemedianvalue):
&nbsp&nbsp&nbsp&nbsp 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]))


One response to “Simple median in python”

  1. Nannette Agron says :

    The weeked I read similar article but this one is 100 times more interesting.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: