DETREND

This function removes either a linear trend or a constant mean from data along a selected axis. It is commonly used as a preprocessing step before decomposition or spectral analysis.

For constant detrending, the transformed data is:

y_t = x_t - \bar{x}

For linear detrending, the best-fit line a t + b is estimated by least squares and subtracted:

y_t = x_t - (a t + b)

The function returns the detrended data as a rectangular 2D array.

Excel Usage

=DETREND(data, axis, detrend_type, breakpoint, overwrite_data)
  • data (list[list], required): 2D range of numeric values.
  • axis (int, optional, default: -1): Axis along which detrending is applied.
  • detrend_type (str, optional, default: “linear”): Type of detrending to apply.
  • breakpoint (int, optional, default: 0): Breakpoint index for piecewise linear detrending.
  • overwrite_data (bool, optional, default: false): Allow in-place operation to avoid copying.

Returns (list[list]): 2D array of detrended values.

Example 1: Linear detrend on a row vector

Inputs:

data axis detrend_type breakpoint overwrite_data
1 2 3 4 5 6 -1 linear 0 false

Excel formula:

=DETREND({1,2,3,4,5,6}, -1, "linear", 0, FALSE)

Expected output:

Result
0 2.22045e-16 4.44089e-16 8.88178e-16 8.88178e-16 1.77636e-15
Example 2: Constant detrend on a row vector

Inputs:

data axis detrend_type breakpoint overwrite_data
3 4 5 6 7 -1 constant 0 false

Excel formula:

=DETREND({3,4,5,6,7}, -1, "constant", 0, FALSE)

Expected output:

Result
-2 -1 0 1 2
Example 3: Linear detrend across rows in a matrix

Inputs:

data axis detrend_type breakpoint overwrite_data
1 2 3 4 1 linear 0 false
2 4 6 8

Excel formula:

=DETREND({1,2,3,4;2,4,6,8}, 1, "linear", 0, FALSE)

Expected output:

Result
7.77156e-16 2.22045e-16 0 -8.88178e-16
1.55431e-15 4.44089e-16 0 -1.77636e-15
Example 4: Constant detrend along axis zero

Inputs:

data axis detrend_type breakpoint overwrite_data
1 2 3 0 constant 0 false
4 5 6
7 8 9

Excel formula:

=DETREND({1,2,3;4,5,6;7,8,9}, 0, "constant", 0, FALSE)

Expected output:

Result
-3 -3 -3
0 0 0
3 3 3

Python Code

import numpy as np
from scipy.signal import detrend as scipy_detrend

def detrend(data, axis=-1, detrend_type='linear', breakpoint=0, overwrite_data=False):
    """
    Remove linear or constant trend from input data.

    See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.detrend.html

    This example function is provided as-is without any representation of accuracy.

    Args:
        data (list[list]): 2D range of numeric values.
        axis (int, optional): Axis along which detrending is applied. Default is -1.
        detrend_type (str, optional): Type of detrending to apply. Valid options: Linear, Constant. Default is 'linear'.
        breakpoint (int, optional): Breakpoint index for piecewise linear detrending. Default is 0.
        overwrite_data (bool, optional): Allow in-place operation to avoid copying. Default is False.

    Returns:
        list[list]: 2D array of detrended values.
    """
    try:
        def to2d(x):
            return [[x]] if not isinstance(x, list) else x

        data = to2d(data)

        if detrend_type not in ("linear", "constant"):
            return "Error: detrend_type must be 'linear' or 'constant'"
        if not isinstance(data, list) or not all(isinstance(row, list) for row in data):
            return "Error: data must be a 2D list"

        matrix = []
        width = None
        for row in data:
            numeric_row = []
            for item in row:
                try:
                    numeric_row.append(float(item))
                except (TypeError, ValueError):
                    return "Error: data must contain only numeric values"

            if width is None:
                width = len(numeric_row)
            elif len(numeric_row) != width:
                return "Error: data must be rectangular"

            matrix.append(numeric_row)

        if not matrix or width == 0:
            return "Error: data must contain at least one numeric value"

        arr = np.asarray(matrix, dtype=float)
        detrended = scipy_detrend(
            arr,
            axis=axis,
            type=detrend_type,
            bp=breakpoint,
            overwrite_data=overwrite_data,
        )

        out = np.asarray(detrended)
        if out.ndim == 1:
            return [[float(v)] for v in out]

        return [[float(v) for v in row] for row in out]
    except Exception as e:
        return f"Error: {str(e)}"

Online Calculator

2D range of numeric values.
Axis along which detrending is applied.
Type of detrending to apply.
Breakpoint index for piecewise linear detrending.
Allow in-place operation to avoid copying.