Note that there are some explanatory texts on larger screens.

plurals
  1. POFinding moving average from data points in Python
    primarykey
    data
    text
    <p>I am playing in Python a bit again, and I found a neat book with examples. One of the examples is to plot some data. I have a .txt file with two columns and I have the data. I plotted the data just fine, but in the exercise it says: Modify your program further to calculate and plot the running average of the data, defined by:</p> <pre><code>$Y_k=\frac{1}{2r}\sum_{m=-r}^r y_{k+m}$ </code></pre> <p>where <code>r=5</code> in this case (and the <code>y_k</code> is the second column in the data file). Have the program plot both the original data and the running average on the same graph.</p> <p>So far I have this:</p> <pre><code>from pylab import plot, ylim, xlim, show, xlabel, ylabel from numpy import linspace, loadtxt data = loadtxt("sunspots.txt", float) r=5.0 x = data[:,0] y = data[:,1] plot(x,y) xlim(0,1000) xlabel("Months since Jan 1749.") ylabel("No. of Sun spots") show() </code></pre> <p>So how do I calculate the sum? In Mathematica it's simple since it's symbolic manipulation (Sum[i, {i,0,10}] for example), but how to calculate sum in python which takes every ten points in the data and averages it, and does so until the end of points?</p> <p>I looked at the book, but found nothing that would explain this :\</p> <hr> <p>heltonbiker's code did the trick ^^ :D</p> <pre><code>from __future__ import division from pylab import plot, ylim, xlim, show, xlabel, ylabel, grid from numpy import linspace, loadtxt, ones, convolve import numpy as numpy data = loadtxt("sunspots.txt", float) def movingaverage(interval, window_size): window= numpy.ones(int(window_size))/float(window_size) return numpy.convolve(interval, window, 'same') x = data[:,0] y = data[:,1] plot(x,y,"k.") y_av = movingaverage(y, 10) plot(x, y_av,"r") xlim(0,1000) xlabel("Months since Jan 1749.") ylabel("No. of Sun spots") grid(True) show() </code></pre> <p>And I got this: </p> <p><img src="https://i.stack.imgur.com/4TyaF.png" alt="image"></p> <p>Thank you very much ^^ :)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload