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>Just go thought second to second to last elements and put save the median out of this, previous and next element. Note that first and last elements are left as they were.</p>

<p>Try this:</p>

<pre><code>lat = [50.63757782, 50.6375742, 50.6375742, 50.6374077762, 50.63757782, 50.6374077762, 50.63757782, 50.63757782]

# returns median value out of the three values
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


# add the first element
filtered = [lat[0]]

for i in range(1, len(lat) - 1):
    filtered += [median(lat[i - 1], lat[i], lat[i + 1])]

# add the last element
filtered += [lat[-1]]

print(filtered)
</code></pre>

<p>What you are doing is a very basic <a href="https://en.wikipedia.org/wiki/Median_filter" rel="nofollow">Median filter</a></p>

python numpy replace median imputation