xarray select\interpolate custom 1D slice out auf multidimensional data (aka zip vs itertools.product)

Viewed 374

I have a (large) multidimensional xarray Dataarray or Dataset and would like to select or interpolate data along a 1D path without slow for loops or list comprehension (e.g. there is 2D data defined on Latitudes and Longitudes, and i would like to get the data along a path given by latitudes and longitudes):

import xarray as xr
import numpy as np

lats, lons = np.arange(0, 6), np.arange(10, 17)
path_lats, path_lons = np.arange(0.3, 5, 0.5), np.arange(10.6, 15.6, 0.5)

da = xr.DataArray(np.random.rand(len(lats), len(lons)), coords=[lats, lons], dims=['latitude', 'longitude'])

The following returns a 2D DataArray containing all combinations of path_lats and path_lons, similar to a for loop using itertools.product(path_lats, path_lons):

da_path = da.interp(latitude=path_lats, longitude=path_lons)

For larger Dataarrays\Datasets with more than two dimension this will consume a lot of memory because it contains a lot of data that is not needed for this task.

What i would like to have is a fast version of a for loop \ list comprehension using zip(path_lats, path_lons), e.g. something like (not valid syntax here)

da_pathZIP = da.interp((latitude, longitude) = (path_lats, path_lons))

which would return a 1D Dataarray (coordinate: index of the path) and maybe the latitudes and longitudes additional to the data. The resulting Datarray should contain the following data:

[float(da.interp(latitude=p_lat, longitude=p_lon)) for p_lat, p_lon in zip(path_lats, path_lons)]

Is this possible in xarray without using loops?

1 Answers

nevermind, i just found the solution in the xarray docs:

da_lons = xr.DataArray(path_lons, dims='time')
da_lats = xr.DataArray(path_lats, dims='time')
da_pathZIP = da.interp(latitude=da_lats, longitude=da_lons)
Related