Last active
November 19, 2023 05:47
-
-
Save rabernat/1ea82bb067c3273a6166d1b1f77d490f to your computer and use it in GitHub Desktop.
Detrend xarray DataArrays using polyfit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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!
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
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!