Replace some values in DataArray based on list of indices

Viewed 28

In xarray, I have a larger time series that I want to replace some of the values with what is in a smaller time series. The times in the new time series are a strict subset of the larger.

import xarray as xr
import numpy as np

ds = xr.DataArray(data=np.arange(5),
                  dims=["time"],
                  coords={'time': [0, 1.1, 2.3, 4.5, 7.8]})

fixtime = [1.1, 4.5, 7.8]
fixdata = [10, 11, 12]

should yield ds.data == [0, 10, 2, 11, 12].

Of course, I can easily do this with a for-loop,

for t, d in zip(fixtime, fixdata):
    ds[t==ds.time] = d

but there is likely a more elegant way for larger data sets?

1 Answers

One option would be to make your fixdata into a DataArray, reindex the new DataArray onto the existing coordinates, and use .where():

import xarray as xr
import numpy as np

ds = xr.DataArray(data=np.arange(5),
                  dims=["time"],
                  coords={'time': [0, 1.1, 2.3, 4.5, 7.8]})

dsfix = xr.DataArray([10, 11, 12], 
                     dims='time', 
                     coords={'time': [1.1, 4.5, 7.8]})

dsfix = dsfix.reindex_like(ds)

ds = dsfix.where(~dsfix.isnull(), ds)

You could also use bracket notation: ds[~dsfix.isnull()] = dsfix[~dsfix.isnull()]

Related