Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kuchaale/0c3fb48e1450b47eea160a662fb0735e to your computer and use it in GitHub Desktop.
Save kuchaale/0c3fb48e1450b47eea160a662fb0735e to your computer and use it in GitHub Desktop.
import xarray as xr
import numpy as np
# create an example dataset
da = xr.DataArray(np.random.rand(10,30,40), dims=['time', 'lat', 'lon'])
# define a function to compute a linear trend of a timeseries
def linear_trend(x):
pf = np.polyfit(x.time, x, 1)
# we need to return a dataarray or else xarray's groupby won't be happy
return xr.DataArray(pf[0])
# stack lat and lon into a single dimension called allpoints
stacked = da.stack(allpoints=['lat','lon'])
# apply the function over allpoints to calculate the trend at each point
trend = stacked.groupby('allpoints').apply(linear_trend)
# unstack back to lat lon coordinates
trend_unstacked = trend.unstack('allpoints')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment