Search code examples
pythonnumpyindexingmedian

median of five points python


My data frame (df) has a list of numbers (total 1773) and I am trying to find a median for five numbers (e.g. the median of 3rd number = median (1st,2nd,3rd,4th,5th))

num
10
20
15
34
...
...
...

def median(a, b, c,d,e):
    I=[a,b,c,d,e]
    return I[2]



num_median = [num[0]]

for i in range(1, len(num)):
    num_median = median(num[i - 1], num[i-2], num[i],num[i+1],num[i+2])

df['num_median']=num_median


IndexError: index 1773 is out of bounds for axis 0 with size 1773

Where did it go wrong and Is there any other method to compute the median?


Solution

  • An example which will help:

    a = [0, 1, 2, 3]
    print('Length={}'.format(len(a)))
    print(a(4))
    

    You are trying the same thing. The actual index of an element is one lower than the place it is. Keep in mind your exception shows you exactly where your problem is.

    You need to modify:

    for i in range(1, len(num) - 2):
        num_median = median(num[i - 1], num[i-2], num[i],num[i+1],num[i+2])
    

    So that your last index check will not be too large. Otherwise, when you are at the end of your array (index = 1773) you will be trying to access an index which doesn't exist (1773 + 2).