How can i find the median of a number from a list? Python
Here's a nice trick to avoid using if
/else
to handle the odd and even length cases separately: the indices in the middle are (len(nums) - 1) // 2
and len(nums) // 2
. If the length is odd, then these indices are equal, so adding the values and dividing by 2 has no effect.
Note that you should do floor-division with the //
operator to get an integer to use as an index.
def median(nums):
nums = sorted(nums)
middle1 = (len(nums) - 1) // 2
middle2 = len(nums) // 2
return (nums[middle1] + nums[middle2]) / 2
Examples:
>>> median([1, 2, 3, 4])
2.5
>>> median([1, 2, 3, 4, 5])
3.0
Python - median value of a list
You could also use NumPy's built-in functions, which could potentially be faster.
import numpy as np
def median(x):
return np.median(np.array(x))
NumPy has a whole suite of array-based data analysis functions, such as Mean, Mode, Range, Standard Deviation and more: https://docs.scipy.org/doc/numpy/reference/routines.statistics.html
Hope this helps!
How do I find the median of a list in python
Hello User9123,
Main Use of the Medain() function
This module provides functions for calculating mathematical statistics of numeric (Real-valued) data
.
Note Unless explicitly noted otherwise, these functions support int, float, decimal.Decimal and fractions.Fraction. Behaviour with other types (whether in the numeric tower or not) is currently unsupported. Mixed types are also undefined and implementation-dependent. If your input data consists of mixed types, you may be able to use map() to ensure a consistent result, e.g. map(float, input_data).
Your Problem
When you use this function for the string so it is not work properly some time so better i suggest you used custom function. I give the solution in my below code.
Explanation Function Median()
statistics.median(data)
Return the median (middle value) of numeric data, using the common “mean of middle two” method. If data is empty, StatisticsError is raised. data can be a sequence or iterator.
The median is a robust measure of central location, and is less affected by the presence of outliers in your data. When the number of data points is odd, the middle data point is returned:
Solution of Problem
If you use this function for the numeric value so try this below code,
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
print getMedian([0,1,2,3,4,5]) # output = 2.5
If you are use median function for the string so try this below code,
def medianFind(mystring):
return mystring[(len(mystring)-1)/2] #len returns the length of the string
print medianFind("vmr") #prints m
I hope my answer is helpful.
If any query so comment please.
Median of a List in Python
Exception is caused by /
operator that returns float
on Python 3.x. Use integer division //
instead when calculating the index:
>>> 2 / 1
2.0
>>> 2 // 1
2
Finding median of a list using quick select and median-of-medians
int finalMedian = quick_select(arrayofMedians, 0, numberOfGroups-1,rank);
Here rank
is wrong - it is set to the middle of array A
, but should rather be the middle of array arrayofMedians
. Change to:
int finalMedian = quick_select(arrayofMedians, 0, numberOfGroups-1, ctr/2);
Also in the function int median_of_medians(int A[], int p, int r)
you're indexing array A
always from index 0 on, while indexing should rather start at p
. To correct this, insert A += p;
near the start of the function.
Finding median of a list of list of different length
Without the overhead of numpy you could do this:
values = [
[1, 1, 1, 18, 35, 35, 70, 133, 280],
[1, 1, 1, 53, 90, 101, 130, 148, 178],
[1, 1, 1, 18, 35, 133, 133, 164],
[1, 1, 1, 18, 101, 108],
[1, 1, 18, 36, 86, 118, 126]
]
def median(list_):
m = len(list_) // 2
list_ = sorted(list_) # to ensure compatibility with numpy.median
if len(list_) % 2 == 0:
return sum(list_[m-1:m+1]) / 2
else:
return float(list_[m])
for e in values:
print(median(e))
Output:
35
90
26.5
9.5
36
Related Topics
Converting Epoch Time into the Datetime
Use Cases for the 'Setdefault' Dict Method
Python - Extracting and Saving Video Frames
Error: " 'Dict' Object Has No Attribute 'Iteritems' "
How to Filter Rows Containing a String Pattern from a Pandas Dataframe
How to Disable Log Messages from the Requests Library
How to Run Spyder in Virtual Environment
How to Get the Different Parts of a Flask Request's Url
What Is the '@=' Symbol for in Python
Difference Between Two Dates in Python
Start a Function at Given Time
Python' Is Not Recognized as an Internal or External Command
In Python, Differencebetween ".Append()" and "+= []"