replacing value with median in python
<pre><code>lat
50.63757782
50.6375742
50.6375742
50.6374077762
50.63757782
50.6374077762
50.63757782
50.63757782
</code></pre>

<p>I have plotted a graph with these latitude values and noticed that there was sudden spike in the graph (outlier). I want to replace every lat value with median of last three values so that I can see a meaningful result</p>

<p>The output might be</p>

<pre><code>lat               lat_med
50.63757782 50.63757782
50.6375742  50.6375742
50.6375742  50.6375742
50.63740778 50.6375742
50.63757782 50.6375742
50.63740778 50.6375742
50.63757782 50.6375742
50.63757782 50.6375742
</code></pre>

<p>I have thousands of such lat values and need to solve this using a for loop. I know that the following code has errors and since I am a beginner in python, I appreciate your help in solving this.</p>

<pre><code>for i in range(0,len(df['lat'])):
    df['lat_med'][i]=numpy.median(numpy.array(df['lat'][i],df['lat'][i-2]))
</code></pre>

<p>I just realized that median calculation for three points is not serving my purpose and I need to consider five values. is there a way to change the median function for as many as values I want. Thank you for your help</p>

<pre><code>def median(a, b, c):
    if a &gt; b and a &gt; c:
        return b if b &gt; c else c

    if a &lt; b and a &lt; c:
        return b if b &lt; c else c

    return a
</code></pre>

<p>You seem to be using <code>pandas</code>' <code>Dataframe</code> structures, so:</p>

<pre><code>import pandas as pd
import numpy as np

df = pd.DataFrame({'lat' : [50.63757782,
                            50.6375742,
                            50.6375742,
                            50.6374077762,
                            50.63757782,
                            50.6374077762,
                            50.63757782,
                            50.63757782]})

def replace_values_with_medians(array):
    last = array.shape[0]-2
    index = 0
    result = np.zeros(last)
    while index &lt; last:
        result[index] = np.median(array[index:index+3])
        index += 1
    return result

lat_med_df = pd.DataFrame({'lat_med':replace_values_with_medians(df['lat'])})
df = pd.concat([df,lat_med_df], axis = 1)
del lat_med_df
</code></pre>

<p>With the result:</p>

<pre><code>&gt;&gt;&gt; df
         lat    lat_med
0  50.637578  50.637574
1  50.637574  50.637574
2  50.637574  50.637574
3  50.637408  50.637408
4  50.637578  50.637578
5  50.637408  50.637578
6  50.637578        NaN
7  50.637578        NaN
</code></pre>

python numpy replace median imputation