Simple Method to Calculate Median in Python
March 17, 2008
(Note: Please see my latest posts at my new blog!)
def getMedian(numericValues):
theValues = sorted(numericValues)
if len(theValues) % 2 == 1:
return theValues[(len(theValues)+1)/2-1]
else:
lower = theValues[len(theValues)/2-1]
upper = theValues[len(theValues)/2]
return (float(lower + upper)) / 2
def validate(valueShouldBe, valueIs):
print “Value Should Be: %.6f, Value Is: %.6f, Correct: %s” % (valueShouldBe, valueIs, valueShouldBe==valueIs)
validate(2.5, getMedian([0,1,2,3,4,5]))
validate(2, getMedian([0,1,2,3,4]))
validate(2, getMedian([3,1,2]))
validate(3, getMedian([3,2,3]))
validate(1.234, getMedian([1.234, 3.678, -2.467]))
validate(1.345, getMedian([1.234, 3.678, 1.456, -2.467]))
Entry Filed under: CodeSnippet, Python, Statistics. Tags: Python, Statistics.
6 Comments Add your own
Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed
1. cw | September 30, 2008 at 4:00 am
one less computation if you do this instead:)
return theValues[(len(theValues)-1)/2]
2. drgoettel | July 16, 2009 at 10:05 am
this doesn’t work for continuos variables…
does it?
3. utah_guy | July 16, 2009 at 2:11 pm
You mean the code in the post? Or the one in the first comment?
4. drgoettel | July 16, 2009 at 4:31 pm
both.
A simply way to calculate median in python is using numpy module, you can read documentation at http://docs.scipy.org/doc/numpy/user/
5. utah_guy | October 9, 2009 at 6:05 pm
It should work for both. The numpy module can be used, too. This is partially for instructional purposes but also for those who don’t want to install external libraries such as numpy.
6. utah_guy | October 9, 2009 at 6:07 pm
Actually, I should correct that statement. This is designed to work with integers and floats. It should also work with discrete variables with some minor tweaks.