I want to apply a function to every grid point of a data array and keep the attributes of the coordinates. Is stack and map the right way to do that?
I tried using stack and map but it lost the coordinate attributes. Adding keep_attrs=True to map gives an error too.
import numpy as np
import xarray as xr
from scipy import stats
from matplotlib import pyplot as plt
%config InlineBackend.figure_format = 'retina'
%matplotlib inline
def ks_test_map(x, t_ind1, t_ind2):
ks_statistic,p_value = stats.ks_2samp(x.isel(T = t_ind1),x.isel(T = t_ind2))
return xr.DataArray(p_value)
t_range = 'T/(Jan 1979)/(Aug 2020)/RANGE/'
JJA = 'T/3/runningAverage/T/(Jun-Aug)VALUES/'
prcp_url = global_prcp + JJA + 'dods'
prcp_ds = xr.open_dataset(prcp_url, decode_times=False)
da = prcp_ds.prcp_est
t_ind1 = np.full_like(prcp_ds.T.values, False, dtype=bool)
t_ind2 = np.full_like(prcp_ds.T.values, False, dtype=bool)
t_ind1[0:10] = True
t_ind2[10:20] = True
stacked = da.stack(allpoints=['X','Y'])
stacked_p = stacked.groupby('allpoints').map(ks_test_map, args=(t_ind1, t_ind2))
p_map = stacked_p.unstack('allpoints')
p_map.plot()