Skip to content

Instantly share code, notes, and snippets.

@rabernat
Last active November 19, 2023 05:47
Show Gist options
  • Save rabernat/1ea82bb067c3273a6166d1b1f77d490f to your computer and use it in GitHub Desktop.
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
@xiuyongwu
Copy link

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