user5618251
user5618251

Reputation: 361

How to add a new variable to xarray.Dataset in Python with same time,lat,lon dimensions with assign?

I have an xarray.Dataset that looks like:

print(ds2)
<xarray.Dataset>
Dimensions:      (time: 46, latitude: 360, longitude: 720)
Coordinates:
  * time         (time) datetime64[ns] 1976-01-01 1977-01-01 ... 2021-01-01
  * latitude     (latitude) float64 89.75 89.25 88.75 ... -88.75 -89.25 -89.75
  * longitude    (longitude) float64 -179.8 -179.2 -178.8 ... 178.8 179.2 179.8
Data variables:
    Glacier      (time, latitude, longitude) float64 dask.array<chunksize=(1, 360, 720), meta=np.ndarray>
    Uncertainty  (time, latitude, longitude) float64 dask.array<chunksize=(1, 360, 720), meta=np.ndarray>

I also have a raster with similar dimensions:

print(np.shape(rgi_raster))
(1, 360, 720)

How do I add rgi_raster to the xarray.Dataset so that it has the same time,lat,lon coordinates at the Glacier and Uncertainty variable?

I tried:

ds2=ds2.assign(rgi_raster=rgi_raster)

But this gives:

<xarray.Dataset>
Dimensions:      (time: 46, latitude: 360, longitude: 720, band: 1, x: 720,
                  y: 360)
Coordinates:
  * time         (time) datetime64[ns] 1976-01-01 1977-01-01 ... 2021-01-01
  * latitude     (latitude) float64 89.75 89.25 88.75 ... -88.75 -89.25 -89.75
  * longitude    (longitude) float64 -179.8 -179.2 -178.8 ... 178.8 179.2 179.8
  * band         (band) int64 1
  * x            (x) float64 -179.8 -179.2 -178.8 -178.2 ... 178.8 179.2 179.8
  * y            (y) float64 -89.75 -89.25 -88.75 -88.25 ... 88.75 89.25 89.75
    spatial_ref  int64 0
Data variables:
    Glacier      (time, latitude, longitude) float64 dask.array<chunksize=(1, 360, 720), meta=np.ndarray>
    Uncertainty  (time, latitude, longitude) float64 dask.array<chunksize=(1, 360, 720), meta=np.ndarray>
    rgi_raster   (band, y, x) float64 19.0 19.0 19.0 19.0 ... 10.0 10.0 10.0

Upvotes: 0

Views: 47

Answers (1)

jhamman
jhamman

Reputation: 6444

If you know the coordinates are the same, you can construct a DataArray directly and add it to the Dataset:

ds['rgi_raster'] = xr.DataArray(rgi_raster, dims=('band', 'latitude', 'longitude'))

Note: your example raster has a first dimension with a shape 1. This can't be time but it can be something else (e.g. Band).

Upvotes: 0

Related Questions