Real-world signals often ride on top of an underlying trend, a slow drift upward or downward, that can obscure the more interesting fluctuations you actually want to analyze; detrend() fits and subtracts that trend, leaving just the residual variation around it. type='linear', the default, fits and removes a straight-line trend, while type='constant' simply subtracts the mean, removing only a constant offset rather than any slope.
1Understanding signal.detrend()
Real-world signals often ride on top of an underlying trend, a slow drift upward or downward, that can obscure the more interesting fluctuations you actually want to analyze; detrend() fits and subtracts that trend, leaving just the residual variation around it. type='linear', the default, fits and removes a straight-line trend, while type='constant' simply subtracts the mean, removing only a constant offset rather than any slope.
Use type='constant' instead of the default type='linear' when you only want to center the data around zero by removing its mean, without also removing any actual linear trend/drift the data might have.
from scipy import signal
import numpy as np
data = np.array([1.1, 2.8, 5.1, 6.9, 9.1])
detrended = signal.detrend(data)
print(np.round(detrended, 2))2Practical Example
Here is a real-world application of signal.detrend() showing how it is used in production SciPy code.
from scipy import signal
import numpy as np
data = np.array([10.0, 10.0, 10.0, 10.0])
detrended = signal.detrend(data, type="constant")
print(detrended)3Best Practices
Follow these guidelines when working with signal.detrend():
1. Detrend a signal before frequency-domain analysis, like an FFT, since a strong low-frequency trend can dominate and obscure the higher-frequency components you actually care about
2. Choose type='constant' vs type='linear' deliberately based on whether the data has an actual slope worth removing, or just needs centering around its mean
3. Visually inspect the detrended result against the original to confirm the trend removal looks reasonable, rather than assuming it always behaves as expected
Tip: Use type='constant' instead of the default type='linear' when you only want to center the data around zero by removing its mean, without also removing any actual linear trend/drift the data might have.
from scipy import signal
import numpy as np
data = np.array([1.1, 2.8, 5.1, 6.9, 9.1])
detrended = signal.detrend(data)
print(np.round(detrended, 2))