Does Xarray support numpy computation functions such as polyfit? Or is there an efficient way to apply such functions to datasets?
Example: I want to calculate the slope of a line fitted to two variables (Temperature and Height), to calculate a lapse rate. I have a dataset (below) with these two variables with dimensions of (vertical, time, xgrid_0, ygrid_0).
<xarray.Dataset>
Dimensions: (PressLev: 7, time: 48, xgrid_0: 685, ygrid_0: 485)
Coordinates:
gridlat_0 (ygrid_0, xgrid_0) float32 44.6896 44.6956 44.7015 44.7075 ...
gridlon_0 (ygrid_0, xgrid_0) float32 -129.906 -129.879 -129.851 ...
* ygrid_0 (ygrid_0) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...
* xgrid_0 (xgrid_0) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...
* time (time) datetime64[ns] 2016-08-15T01:00:00 2016-08-15T02:00:00 ...
* PressLev (PressLev) int64 0 1 2 3 4 5 6
Data variables:
Temperature (PressLev, time, ygrid_0, xgrid_0) float64 289.4 289.4 289.4 ...
Height (PressLev, time, ygrid_0, xgrid_0) float64 85.23 85.13 84.98 ...
If I extract the Temperature and Height for a given time, xgrid_0, ygrid_0; I can use the numpy.polyfit function.
ds_LR = ds.TMP_P0_L103_GST0 * 0 -9999 # Quick way to make dataarray with -9999 values but with correct dims/coords
for cts in np.arange(0,len(ds_UA.time)):
for cx in ds_UA.xgrid_0.values:
for cy in ds_UA.ygrid_0.values:
x_temp = ds_UA.Temperature[:,cts,cy,cx] # Grab the vertical profile of air temperature
y_hgt = ds_UA.Height[:,cts,cy,cx] # Grab the vertical heights of air temperature values
s = np.polyfit(y_hgt,x_temp,1) # Fit a line to the data
ds_LR[cts,cy,cx].values = s[0] # Grab the slope (first element)
But this is a slow and inefficient approach. Any suggestions on a better way to approach this?
来源:https://stackoverflow.com/questions/38960903/applying-numpy-polyfit-to-xarray-dataset