Optimization of for loop in python
<p>I am executing the following code for different time stamps and each will have close to one million records. It took more than one hour for one date and I have the data for a total of 35 dates.</p>

<p>Is there a way to optimize this code?</p>

<pre><code>def median(a, b, c,d,e):
    I=[a,b,c,d,e]
    I.sort()
    return I[2]

for i in range(2, len(df['num'])-2):
    num_smooth= median(df['num'][i-1], df['num'][i-2], df['num'][i],
                       df['num'][i+1], df['num'][i+2])
    df.set_value(i,'num_smooth',num_smooth)
df['num_smooth'].fillna(df['num'], inplace=True)

...........................................
Remaining code
</code></pre>

<p>A nice tool for profiling python code performance line by line is <a href="https://github.com/rkern/line_profiler" rel="nofollow">kernprof</a>.</p>

python loops pandas for-loop optimization