-
OverviewIs there a clean way in Xarray to reindex or a DataArray based on a 2D coordinate like I provide code for mock input data and show my desired result after outlining my motivation. MotivationI'm fairly new to Xarray, and I feel like the following problem should have an elegant solution, but unfortunately I'm not finding it, even after spending significant time thinking and experimenting. I hope there is a simple answer that I just haven't discovered yet. I'm working with some gridded climatological data; essentially a 3D Concrete example: input/desired outputFor my purposes, I can use the approximation local_time = utc_time + round(lon / 15) * HOUR Note that InputFor simplicity I'm going to ignore import xarray as xr
import numpy as np
import pandas as pd
utc_time = pd.to_datetime(["2020-01-01 12:00", "2020-01-01 15:00"])
lon = [-45, 0, 45]
da = xr.DataArray(
273 + np.arange(6).reshape(2, 3),
coords=[("utc_time", utc_time), ("lon", lon)],
name="temperature",
)
da = da.assign_coords(local_time=da.utc_time + pd.Timedelta(hours=1) * da.lon / 15)
"""
<xarray.DataArray 'temperature' (utc_time: 2, lon: 3)>
array([[273, 274, 275],
[276, 277, 278]])
Coordinates:
* utc_time (utc_time) datetime64[ns] 2020-01-01T12:00:00 2020-01-01T15:0...
* lon (lon) int64 -45 0 45
local_time (utc_time, lon) datetime64[ns] 2020-01-01T09:00:00 ... 2020-0...
""" Desired output:"""
<xarray.DataArray 'temperature' (local_time: 4, lon: 3)>
array([[273., nan, nan],
[276., 274., nan],
[ nan, 277., 275.],
[ nan, nan, 278.]])
Coordinates:
* local_time (local_time) datetime64[ns] 2020-01-01T09:00:00 ... 2020-01-0...
* lon (lon) int64 -45 0 45
utc_time (local_time, lon) datetime64[ns] 2020-01-01T12:00:00 ... 2020...
""" Note how the values are shifted vertically in the time dimension according to an offset determined by longitude dimension. My question is not about how to generate the NumPy array of the result. It's about if I can use Xarray's coordinate machinery to generate the above result in a relatively declarative manner, without performing error-prone and confusing index manipulations by hand. OPTIONAL: The approaches I've already attemptedI've actually gone substantially further in the following approaches than shown here. Apologies if this isn't so coherent, since it's tricky to judge what's useful or not from a failed approach.
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Your intuition is correct, you'll just need to use flox to execute though.
This simpler groupby works too: import flox.xarray
flox.xarray.xarray_reduce(
da, da.local_time, func="first", dim="utc_time", fill_value=np.nan
).transpose() |
Beta Was this translation helpful? Give feedback.
-
@benbovy this does truly feel like a reindexing problem, do you think it could be made to work |
Beta Was this translation helpful? Give feedback.
Your intuition is correct, you'll just need to use flox to execute though.
This simpler groupby works too: