Detrending Data in Python with Numpy

Warning: This post is several years old and the author has marked it as poor quality (compared to more recent posts). It has been left intact for historical reasons, but but its content (and code) may be inaccurate or poorly written.

While continuing my quest into the world of linear data analysis and signal processing, I came to a point where I wanted to emphasize variations in FFT traces. While I am keeping my original data for scientific reference, visually I want to represent it emphasizing variations rather than concentrating on trends. I wrote a detrending function which I’m sure will be useful for many applications:

def detrend(data,degree=10):
 detrended=[None]*degree
 for i in range(degree,len(data)-degree):
 chunk=data[i-degree:i+degree]
 chunk=sum(chunk)/len(chunk)
 detrended.append(data[i]-chunk)
 return detrended+[None]*degree

However, this method is extremely slow. I need to think of a way to accomplish this same thing much faster. [ponders]

UPDATE: It looks like I’ve once again re-invented the wheel. All of this has been done already, and FAR more efficiently I might add. For more see scipy.signal.detrend.html

import scipy.signal
ffty=scipy.signal.detrend(ffty)