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
@aidenrobert
Copy link

Hey! This was a useful snippet of code for easy detrending, but I just wanted to say that it doesn't work as it is — when you pass 'dim' to xarray.polyval, it only reads a string, but it needs a coordinate type. I made it work by changing line 6 to:

fit = xr.polyval(da[dim], p.polyfit_coefficients)

Thanks for sharing!

@krlosbatist
Copy link

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

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