Skip to content

Instantly share code, notes, and snippets.

@rabernat
Created June 1, 2016 12:00
Show Gist options
  • Save rabernat/bc4c6990eb20942246ce967e6c9c3dbe to your computer and use it in GitHub Desktop.
Save rabernat/bc4c6990eb20942246ce967e6c9c3dbe 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')
@sudhansu-s-rath
Copy link

How the xarray.polyfit different from this ?

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