Skip to content

Instantly share code, notes, and snippets.

@rabernat
Last active December 18, 2024 05:21
Show Gist options
  • Select an option

  • Save rabernat/1ea82bb067c3273a6166d1b1f77d490f to your computer and use it in GitHub Desktop.

Select an option

Save rabernat/1ea82bb067c3273a6166d1b1f77d490f to your computer and use it in GitHub Desktop.
Detrend xarray DataArrays using polyfit
import xarray as xr
def detrend_dim(da, dim, deg=1):
# detrend along a single dimension
p = da.polyfit(dim=dim, deg=deg)
fit = xr.polyval(dim, p.polyfit_coefficients)
return da - fit
def detrend(da, dims, deg=1):
# detrend along multiple dimensions
# only valid for linear detrending (deg=1)
da_detrended = da
for dim in dims:
da_detrended = detrend_dim(da_detrended, dim, deg=deg)
return da_detrended
@krlosbatist
Copy link
Copy Markdown

Hello!!!
I would like to know how to adjust the polynomial to remove the non-linear trend using xarray... Does anyone have any suggestions? I'm new to python

Thanks!

@xiuyongwu
Copy link
Copy Markdown

Hi, how to apply this function to xarray dataset?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment